Java Multi-Threading understanding and examples

Source: Internet
Author: User

A method that is often used to write a multithreaded program: Run (), start (), Wait (), notify (), Notifyall (), sleep (), yield (), join ()

There is also a keyword: synchronized

Here are the main words:

The way threads are created does not need to be elaborate, in 2 ways thread and runnable

1.run () and start ()

Example 1:

 Public class extends Thread {publicvoid  run () { for (int i = 0; i < i++) {Syst Em.out.print ("" + I);}}  Public Static void Main (string[] args) {new  threadtest (). Start (); New threadtest (). Start ();}}

This is a simple multi-threaded example

Example 2:

 Public classThreadTestImplementsRunnable { Public synchronized voidrun () { for(inti = 0; I < 10; i++) {System.out.print (" " +i);}} Public Static voidMain (string[] args) {Runnable R1=Newthreadtest (); Runnable R2=Newthreadtest (); Thread T1=NewThread (R1); Thread T2=NewThread (R2); T1.start (); T2.start ();}}

In this example, run is added synchronized, what is the result of this program output? T1 and T2 are threads of 2 objects, different objects have different threads, so synchronized in this program does not work, and for the definition of synchronized, it is for multiple threads of the same object, Only one thread at a time can access the data for this object

Example 3:

 Public classThreadTestImplementsRunnable { Public synchronized voidrun () { for(inti = 0; I < 10; i++) {System.out.print (" " +i);}} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T1=NewThread (R); Thread T2=NewThread (R); T1.start (); T2.start ();}}

Example 4:

 Public classThreadTestImplementsRunnable { Public voidrun () {synchronized( This) { for(inti = 0; I < 10; i++) {System.out.print (" " +i); }}} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T1=NewThread (R); Thread T2=NewThread (R); T1.start (); T2.start ();}}


In examples 3 and 4,synchronized controls the data sharing of thread objects, the output can only be 0123456789,3 and 4 in fact, the difference is synchronized scope

Example 5:

 Public classThreadTestImplementsRunnable { Public voidrun () { for(intk = 0; K < 5; k++) {System.out.println (Thread.CurrentThread (). GetName ()+ ": For loop:" +k);}synchronized( This) { for(intk = 0; K < 5; k++) {System.out.println (Thread.CurrentThread (). GetName ()+ ": Synchronized for Loop:" +k); }}} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T1=NewThread (R, "T1_name"); Thread T2=NewThread (R, "T2_name"); T1.start (); T2.start ();}}

The output is:

T1_name:for loop:0
T1_name:for loop:1
T1_name:for Loop:2
T2_name:for loop:0
T1_name:for Loop:3
T2_name:for loop:1
T1_name:for Loop:4
T2_name:for Loop:2
T1_name:synchronized for loop:0
T2_name:for Loop:3
T1_name:synchronized for Loop:1
T2_name:for Loop:4
T1_name:synchronized for Loop:2
T1_name:synchronized for Loop:3
T1_name:synchronized for Loop:4
T2_name:synchronized for loop:0
T2_name:synchronized for Loop:1
T2_name:synchronized for Loop:2
T2_name:synchronized for Loop:3
T2_name:synchronized for Loop:4

The first for loop does not receive synchronized protection, so the T1,T2 is interleaved and the second loop is protected by synchronized, so the result is regular

2.sleep () Method:

Example 6:

public class ThreadTest implements Runnable {
public void Run () {

for (int k = 0; k < 5; k++) {
if (k = = 2) {
try {
Thread.CurrentThread (). Sleep (5000);
}
catch (Exception e) {}
}
System.out.println (Thread.CurrentThread (). GetName () + ":" + K);
}
}

public static void Main (string[] args) {
Runnable r = new ThreadTest ();
thread T1 = new Thread (R, "T1_name");
Thread t2 = new Thread (R, "T2_name");
T1.setpriority (thread.max_priority);
T2.setpriority (thread.min_priority);
T1.start ();
T2.start ();
}
}

Output Result:

t1_name:0
T1_name:1
t2_name:0
T2_name:1
T1_name:2
T1_name:3
T1_name:4
T2_name:2
T2_name:3
T2_name:4

T1 is set to the highest priority, T2 is set to the lowest priority, T1 does not finish, T2 will not be able to execute. But because T1 in the middle of the execution of the break for 5 seconds, which makes T2 have the opportunity to execute.

3.join () Method: basically let the thread of the call modification method finish the thing inside the run method, after executing the code after the join () method

Example 7:

 Public classThreadTestImplementsRunnable { Public Static intA = 0; Public voidrun () { for(intk = 0; K < 5; k++) {a= A + 1;}} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T=NewThread (R); T.start (); System.out.println (a);}}

Example 8:

 Public classThreadTestImplementsRunnable { Public Static intA = 0; Public voidrun () { for(intk = 0; K < 5; k++) {a= A + 1;} Public Static voidMain (string[] args)throwsException {Runnable R=Newthreadtest (); Thread T=NewThread (R); T.start (); T.join (); System.out.println (a);}}

The difference between instances 7 and 8 is that a join method is added, and the join ensures that the thread object calling this method completes the contents of the corresponding run method, so instance 7 is not sure what the output is, and instance 8 definitely outputs 5

4.yield () Method:

The yield () method is similar to the sleep () method, except that it cannot be paused by a user-specified thread for a long time. According to Sun, the sleep method allows a low-priority thread to be executed and, of course, gives the same priority and high-priority threads the opportunity to execute. The yield () method only enables threads with the same priority to have an opportunity to execute.

Example 9:

 Public classThreadTestImplementsRunnable { Public voidrun () {8 for(intk = 0; K < 5; k++) {if(k = = 5 && thread.currentthread (). GetName (). Equals ("T1") {Thread.yield ();} System.out.println (Thread.CurrentThread (). GetName ()+ " : " +k);}} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T1=NewThread (R, "T1"); Thread T2=NewThread (R, "T2"); t1.setpriority (thread.max_priority); t2.setpriority (thread.min_priority); T1.start (); T2.start ();}}

Output Result:

t1:0
T1:1
T1:2
T1:3
T1:4

t2:0
T2:1
T2:2
T2:3
T2:4

From the output, theyield () method does not allow threads of different priorities to have an opportunity to execute. In this case, T1 and T2 different priorities, when T1 is yield, T2 is not a chance, only wait until the high-priority T1 execution is completed only after the opportunity to execute, and sleep is not, you can see the example 6

5.wait (), notify (), Notifyall ()

First Note: Wait (), notify (), Notifyall () These methods are provided by the Java.lang.Object class, and the methods described above are provided by the Java.lang.Thread class (the thread class implements the Runnable interface).

These three methods are used to coordinate the access of multiple threads to shared data, so these three methods can only be used in synchronized

Example 10:

 Public classThreadTestImplementsRunnable { Public Static intSharevar = 0;  Public synchronized voidrun () {if(Sharevar = = 0) { for(inti = 0; I < 10; i++) {Sharevar++; if(Sharevar = = 5) {Try{ This. Wait (); }Catch(Exception e) {}}} }if(Sharevar! = 0) {System.out.print (Thread.CurrentThread (). GetName ()); System.out.println ("Sharevar =" +Sharevar);  This. Notify (); }} Public Static voidMain (string[] args) {Runnable R=Newthreadtest (); Thread T1=NewThread (R, "T1");Thread T2=NewThread (R, "T2");  T1.start (); T2.start ();}}

Output Result:

T2 Sharevar = 5
T1 Sharevar = 10

Procedure: The T1 thread executes first. Since the initial state of Sharevar is 0,T1 will cause Sharevar to continuously add 1, when the value of Sharevar is 5 o'clock, T1 calls the Wait () method,
The T1 will be in a resting state while releasing the lock flag. At this point T2 get the lock flag to start execution, the value of Sharevar has changed to 5, so T2 directly output Sharevar value,
Then call the Notify () method to wake the T1. T1 then the last time before the rest of the progress continues to execute, the value of Sharevar has been added to 10, because the value of Sharevar at this moment is not 0,
So T1 will output the value of the Sharevar at this point, and then call the Notify () method, since there is no thread waiting for the lock flag at the moment, so this call statement has no effect.

Java Multi-Threading understanding and examples

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.