Use of Java multi-thread collaboration between threads and wait

Source: Internet
Author: User

(Reprinted please indicate the source: http://blog.csdn.net/buptgshengod)

1. Background

Java multithreading is widely used, especially in android applications. Asynchronous thread collaboration is the difficulty and the key for multi-thread operations, and is also a frequent place for job interviews. Next I will share my experiences.

Several keywords are introduced:

Synchronized: thread lock, so that the system only executes the current thread.

Yyall (): Wake up other locked threads

Wait (): suspends a thread.

ExecutorService exec = Executors. newCachedThreadPool ();: Creates a thread pool.

Exec.exe cute (new Runnable (): Place threads in the thread pool for management.

2. Code Section

(1)

public class Thread2 {     public void m4t1() {          synchronized(this) {               int i = 5;               while(i>0) {                    System.out.println("1");                    i--;                    try {                         Thread.sleep(500);                    } catch (InterruptedException ie) {                    }               }          }     }     public void m4t2() {        // synchronized(this){         int i = 5;          while( i > 0) {               System.out.println("2");               i--;               try {                    Thread.sleep(500);               } catch (InterruptedException ie) {               }          }     }     public static void main(String[] args) {          final Thread2 myt2 = new Thread2();          Thread t1 = new Thread(  new Runnable() {  public void run() {  myt2.m4t1();  }  }, "t1"  );          Thread t2 = new Thread(  new Runnable() {  public void run() { myt2.m4t2();   }  }, "t2"  );          t1.start();          t2.start();     }}

We found that one of the two threads was locked and the other was not locked. The running result is as follows. It indicates that although a thread is locked, it can still be accessed by other unlocked threads.

(2)

When we add a lock to both methods <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25np1_vcd4kpha + PHByZSBjbGFzcz0 = "brush: java;"> public class Thread2 {public void m4t1 () {synchronized (this) {int I = 5; while (I> 0) {System. out. println ("1"); I --; try {Thread. sleep (500);} catch (InterruptedException ie) {}}} public void m4t2 () {synchronized (this) {int I = 5; while (I> 0) {System. out. println ("2"); I --; try {Thread. sleep (500);} catch (InterruptedException ie) {}}} public static void main (String [] args) {final Thread2 myt2 = new Thread2 (); thread t1 = new Thread (new Runnable () {public void run () {myt2.m4t1 () ;}, "t1"); Thread t2 = new Thread (new Runnable () {public void run () {myt2.m4t2 () ;}, "t2"); t1.start (); t2.start ();}} The running result is changed

Execute the content in the first lock and then execute the content in the second lock.


(3)

In this case, we use policyall () and wait ()

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Thread2 {     public void m4t1() {          synchronized(this) {               int i = 5;               while(i>0) {                    System.out.println("1");                    i--;                    try {                         Thread.sleep(500);                         notifyAll();                         wait();                    } catch (InterruptedException ie) {                    }               }          }     }     public void m4t2() {        synchronized(this){         int i = 5;          while( i > 0) {               System.out.println("2");               i--;               try {                    Thread.sleep(500);                    notifyAll();                    wait();               } catch (InterruptedException ie) {               }          }        }     }     public static void main(String[] args) {          final Thread2 myt2 = new Thread2();          Thread t1 = new Thread(  new Runnable() {  public void run() {  myt2.m4t1();  }  }, "t1"  );          Thread t2 = new Thread(  new Runnable() {  public void run() { myt2.m4t2();   }  }, "t2"  );          t1.start();          t2.start();     }}

By constantly waking up and then suspending, the two threads run alternately.


(4)

To improve the code, you can put two threads in the thread pool.

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Thread2 {     public void m4t1() {          synchronized(this) {               int i = 5;               while(i>0) {                    System.out.println("1");                    i--;                    try {                         Thread.sleep(500);                         notifyAll();                         wait();                    } catch (InterruptedException ie) {                    }               }          }     }     public void m4t2() {        synchronized(this){         int i = 5;          while( i > 0) {               System.out.println("2");               i--;               try {                    Thread.sleep(500);                    notifyAll();                    wait();               } catch (InterruptedException ie) {               }          }        }     }     public static void main(String[] args) {          final Thread2 myt2 = new Thread2();         ExecutorService exec=Executors.newCachedThreadPool();         exec.execute( new Runnable() {  public void run() {  myt2.m4t1();  }  });         exec.execute( new Runnable() {  public void run() {  myt2.m4t2();  }  });     }}


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.