Java ---- multithreading (1)

Source: Internet
Author: User

Java ---- multi-thread explanation

Multithreading is the last part of Java's basic knowledge and also a difficult point in Java learning. When learning multithreading, it is very necessary to deeply understand its ideas. With the idea of multithreading, it is easy to learn the syntax and rules of multithreading.

1. Introduction to multithreading

Multithreading is the development direction of modern operating systems. Therefore, Java must support multithreading, which features high concurrency and high execution efficiency. Multithreading is an effective means to achieve concurrency. A process can execute multiple tasks concurrently by running multiple threads, and scheduling execution between multiple threads is implemented by the system.

A process is an execution program. multi-process multitasking allows a computer to run two or more programs at the same time. It is also a dynamic execution process, which refers to a complete process from code loading, execution to execution.

A thread is a smaller execution unit than a process. Each part of a process is managed by a thread. Multi-threaded programs require less "management costs" than multi-process programs ". Threads share the same address space and share the same process together, which can save a lot of CPU utilization space, so that the CPU can execute more tasks.

Next, let's look at a sample program that uses multiple threads:

Public class test {

ThreadUseExtends tue = newThreadUseExtends ();

Public static void main (String [] str ){

// Main thread

Test t = new test ();

T. tue. start (); // start the thread

Try {

Thread. sleep (1000); // The Master Thread is suspended for 1 second.

} Catch (Exception e ){

Return;

}

}

Public void PrintA (){

For (int I = 0; I <10; I ++ ){

System. out. println (I + "");

}

}

Public void PrintB (){

For (int I = 10; I <20; I ++ ){

System. out. println (I + "");

}

}

Class ThreadUseExtends extends Thread {

@ Override

Public void run (){

PrintA ();

System. out. println ();

Try {

For (int I = 0; I <10; I ++ ){

Sleep (1000); // thread suspended for 1 second

System. out. print ("*");

}

System. out. println ();

PrintB ();

} Catch (Exception e ){

System. err. println (e );

}

}

}

}

2. How to Create a thread

Thread creation includes creating the main Thread, implementing the Runnable interface, and inheriting the Thread class.

1) creation of the main thread

The main thread of the program runs immediately when the program is started and executed. It is the earliest running thread in all threads, or the thread that generates other subthreads. At the same time, it must execute various closing actions, it is the final thread. The main Thread is automatically created when the program starts, but it can also be controlled by the Thread object. You can use the Thread object to call the currentThread () method to obtain the reference of a main Thread. After obtaining the reference of the main thread, you can control the main thread as you control other threads. The following is an example:

Public static voidmain (String [] str ){

// Obtain the reference of the main thread

Thread t = Thread. currentThread ();

System. out. println ("main thread:" + t );

T. setName ("My main thread ");

System. out. println ("changed name:" + t );

// Thread content

Try {

For (int I = 0; I <5; I ++ ){

System. out. println (I );

T. sleep (1000 );

}

} Catch (Exception e ){

E. printStackTrace ();

}

}

T is the output result when the parameter in the statement println () is used. The sequence is thread name, priority, and group name.

2) Implement the Runnable interface

There are two methods to create a Thread: Implementing the Runnable interface and the process Thread class. The simplest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts an Execution Code unit. You can create a thread for each object by implementing the Runnable interface. To implement the Runnable interface class, you need to define a non-parameter method named run.

The Runnable class can be run without the need to be a sub-class of Thread. You only need to instantiate a Thread object and pass your reference as a parameter to the Thread constructor.

Each execution Thread starts to act as an instance of the Thread class, regardless of the method in which the Thread is created. First, you need to instantiate the Runnable class:

MyRunnable r = newMyRunnable ();

Then you can reference the Runnable class instantiation thread:

Thread t = new MyRunnable ();

The following is an instance that creates a thread by implementing the Runnable interface:

Public class test {

Public static void main (String [] str ){

// Instantiate a thread

MyThread r = new MyThread ();

Thread t = new Thread (r );

T. setPriority (5); // sets the thread priority.

T. start (); // call the run Method

// Main program content

Try {

For (int I = 0; I <10; I ++ ){

System. out. println ("B ");

Thread. sleep (1000 );

}

} Catch (Exception e ){

}

}

}

// Create a thread through the Runnable interface

Class MyThread implementsRunnable {

Int I;

@ Override

Public void run (){

Try {

While (true ){

System. out. println ("a" + I ++ );

Thread. sleep (1000 );

If (I = 10) break;

}

} Catch (Exception e ){

}

}

}

Please carefully study this code and debug it multiple times to observe the printed content. You will have a better understanding of the thread concept and the sequence of multi-thread execution.

3) create a Thread by inheriting the Thread class

The virtual CPU created for the management Thread in Java is an instance of the java. lang. Thread class. It can also be said that the Thread class object is a virtual CPU that runs code and uses data. Multiple Thread objects can share code and data. The method for inheriting the Thread class to create a Thread is: create a new class to inherit the Thread class, and then create an instance of this class. When a class inherits the Thread, it must overload the run () method. Here, the run () method is also the entry to the new Thread. In addition, it must call the start () method to start the new thread for execution. The following is an example:

Public class test {

Public static void main (String [] str ){

// Instantiate a thread

MyThread r = new MyThread ();

R. start (); // call the run () method

R. setPriority (5); // sets the priority.

Try {

For (int I = 0; I <10; I ++ ){

System. err. println ("B ");

Thread. sleep (1000 );

}

} Catch (Exception e ){

}

}

}

// Create a Thread by inheriting the Thread

Class MyThread extends Thread {

Int I;

@ Override

Public void run (){

Try {

While (true ){

System. out. println ("a" + I ++ );

Thread. sleep (1000 );

If (I = 10) break;

}

} Catch (Exception e ){

}

}

}

Compare the above instance with the instance that creates a thread through the Runnable interface, and compare the Code with the printed content, you will find the differences between the two methods and their respective advantages and disadvantages.

4) Comparison of the two methods

The Thread class defines many methods that can be overloaded by its subclass, but only one method must be overloaded, that is, the run () method. This method is also required by the Runnable interface. Therefore, if you do not need to reload other methods of the Thread, it is best to select the method to implement the Runnable interface to create the Thread.

5) create multiple threads

A single thread and dual thread are written in the front face value. The following describes how to create multiple threads. Multithreading can be used to handle the memory allocation of the system to relieve the memory pressure. The following is an example of multithreading:

Public class test {

Public static void main (String [] str ){

// Create three threads

MyThread1 t1 = new MyThread1 ("1st thread ");

MyThread2 t2 = new MyThread2 ("2nd thread ");

MyThread3 t3 = new MyThread3 ("3rd thread ");

T1.start ();

T2.start ();

T3.start ();

}

}

 

Class MyThread1 extendsThread {

String name;

Public MyThread1 (String threadName ){

Name = threadName;

}

@ Override

Public void run (){

Try {

For (int I = 0; I <10; I ++ ){

System. out. println (name + ":" + I );

Thread. sleep (1000 );

}

} Catch (Exception e ){

}

System. err. println (name + "quit ");

}

}

Class MyThread2 extendsThread {

String name;

Public MyThread2 (String threadName ){

Name = threadName;

}

@ Override

Public void run (){

Try {

For (int I = 0; I <10; I ++ ){

System. out. println (name + ":" + I );

Thread. sleep (1000 );

}

} Catch (Exception e ){

}

System. err. println (name + "quit ");

}

}

Class MyThread3 extendsThread {

String name;

Public MyThread3 (String threadName ){

Name = threadName;

}

@ Override

Public void run (){

Try {

For (int I = 0; I <10; I ++ ){

System. out. println (name + ":" + I );

Thread. sleep (1000 );

}

} Catch (Exception e ){

}

System. err. println (name + "quit ");

}

}

If you are a smart person, you will certainly ask, why not just create a Thread class MyThread1, and then instantiate three MyThread1 to start execution? Isn't the code missing? This problem involves the thread priority and concurrent thread execution, which is not easy to understand now. I will explain it in detail below.

The thread constructor is used in the program. It is not directly given in the previous program, but the default constructor of the application. There are many constructors in the thread, including the following types:

> Thread ()

> Thread (Runnable target)

> Thread (Runnable target, String name)

> Thread (String name)

> Thread (ThreadGroup group, Runnable target)

> Thread (ThreadGroup, group, Runnable target, String name)

> Thread (ThreadGroup group, String name)

When a thread is operated, its running results are uncertain, that is, the running results may be different. This is why I asked you to debug and view the printed results repeatedly. However, it is certain that every thread will be started and every thread will be completed.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.