Java multi-thread implementation, java multi-thread implementation

Source: Internet
Author: User

Java multi-thread implementation, java multi-thread implementation

1. What is a thread?

Thread: A single sequential control flow in the program. A relatively independent and schedulable execution unit in a process is the basic unit for Independent System Scheduling and CPU allocation.

Multithreading: a single program runs multiple threads at the same time to complete different tasks. It is called multithreading.

Features:

1) Lightweight processes: the smallest unit that can be executed in the program running flow. threads do not possess system resources, and multiple threads share the resources of the process.

2) one thread can create another thread, and multiple threads can execute concurrently.

3) when multiple threads seize resources in the system running, intermittent interruption may occur. We can see that parallel execution is actually sequential.

4) A process must contain at least one thread, that is, the main thread.

 

2. What are the statuses of threads?

 

 

The thread has five statuses: new, ready, running, blocking, and terminated.

① New: the Thread is created and no method is executed. For example, Thread th = new Thread ().

② Ready: When the start method of the thread is called, the thread state will be changed to ready state, waiting for the cpu to call. A thread in the ready state is scheduled by the cpu. A single cpu does not execute it immediately.

③ Run: When the cpu initiates a call to this thread, it enters the running state.

④ Blocking: When a thread does not have the cpu right for some reason, it will be blocked.

Blocking may occur in the following situations:

1) sleep (long mills): When the parameter is set to milliseconds, the thread is blocked within the specified time period. When the time expires, the thread enters the ready state.

2) suspend () and resume (): suspend will suspend the thread and must execute resume to restore the thread.

3) yield (): similar to sleep (). However, you cannot specify the duration of the pause. You can only assign the opportunity to threads with the same priority without blocking. Like queuing, the front and the back are exchanged, but they are still in the team.

4) wait () and Y (): wait () Enable the thread to enter the blocking state. There are two forms: one is to specify the number of milliseconds, and the other is no parameter. The former can be automatically restored by running y () or beyond the specified time; the latter must be invoked by running y.

5) Synchronization blocking: Wait for synchronization to lock resources. When multiple threads compete for the same resource, only one thread can obtain the lock, and other threads have to wait.

⑤ Termination: The thread is finished or an exception occurs.

3. How to Create a thread?

Java threads can be implemented in three ways: Inheriting the Thread class, implementing the Runnable interface, and using Callable and FutureTask (return values can be returned)

1. Override the run () method by integrating the Thread class

Class MyThread extends Thread {

@ Override

Public void run (){

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

System. out. println (Thread. currentThread (). getName () + "" + I );

}

}

}

 

Public class ThreadDemo {

Public static void main (String [] args ){

System. out. println (Thread. currentThread (). getName ());

MyThread th1 = new MyThread ();

MyThread Th1 = new MyThread ();

Th1.start ();

Th2.start ();

}

}

Output: main

Thread-1 0

Thread-0 0

Thread-1 1

Thread-1 2

......

The logic to be implemented by the thread is written in the run method, and the thread enters the ready state by executing the start () method of the thread, waiting for the CPU to allocate resources.

We can see that two threads are executed in parallel and the CPU is randomly obtained.

 

2. I tried to implement the Runnable interface to implement the run () method.

Class MyThread implements Runnable {

@ Override

Public void run (){

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

System. out. println (Thread. currentThread (). getName () + "" + I );

}

}

}

 

Public class ThreadDemo {

Public static void main (String [] args ){

System. out. println (Thread. currentThread (). getName ());

MyThread th = new MyThread ();

Thread t1 = new Thread (th );

Thread t2 = new Thread (th );

T1.start ();

T2.start ();

}

}

Output: main

Thread-0 0

Thread-0 1

Thread-1 0

Thread-0 2

......

The MyThread instance is passed into the Thread constructor to instantiate the Thread, call the start method of the Thread, and start the Thread.

 

Ps: What is the difference between inheriting the Thread and implementing the Runnable interface?

1: the former is a single inheritance with limitations, but multiple interfaces can be implemented.

2: the latter can share resources.

Runnable is strongly recommended for multithreaded programming.

 

3. Use Callable and Future interfaces to create a thread.

Create an implementation class for the Callable interface and implement the clall () method.

The FutureTask class is used to encapsulate Callable implementation class objects, and the FutureTask object is used as the target of the Thread object to create a Thread.

 

Class MyCallable implements Callable <Integer> {

@ Override

Public Integer call () throws Exception {

Return 1;

}

}

 

Public class ThreadDemo {

Public static void main (String [] args ){

Callable <Integer> myCallable = new MyCallable (); // instantiate MyCallable

FutureTask <Integer> ft = new FutureTask <> (myCallable); // package with FutureTask

 

Thread thread = new Thread (ft); // input FutureTask into Thread construction and instantiate the Thread

Thread. start (); // thread startup

 

Integer result = ft. get (); // get the returned value

System. out. println (result );

 

}

}

1) Implement the call () method in the Callable interface. This is the logic to be executed by the thread.

2) The get () method of FutureTask will be blocked until the call () method is executed and the return value is obtained.

 


Follow ginger to talk about technology, no.: helojava, or scan the following QR code.


One post per day, chicken soup for technical purposes.

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.