Concurrent programming study notes (five threads commonly used method)

table of Contents:

  • sleep()
  • wait()
  • notify()/notifyAll()
  • yieid ()
  • join()
  • to sum up

sleep():

1, the role of sleep () method is to thread suspend specified number of milliseconds

2, sleep () method only temporarily hand over executive power of the CPU , not the lock is released

3, sleep () method does not need to synchronize execution block , and wait () method requires

4, sleep () can () method interrupt by interrupting the sleep state

5, sleep () operation merely thread, and does not involve communication between threads

. 1  public  class SleepTest {
 2      / ** 
. 3       * SLEEP () method does not release the lock, the thread is thus performed in the order
 . 4       * / 
. 5      public  the synchronized  void sleepMethod () {
 . 6          System.out.println ( "Sleep Start: "+ Thread.currentThread () getName ());.
 . 7          the try {
 . 8              the Thread.sleep (1000 );
 . 9          } the catch (InterruptedException E) {
 10              e.printStackTrace ();
 . 11          }
 12 is          System.out.println (" Sleep end: "+. Thread.currentThread () getName ());
 13 is      }
 14  
15      / ** 
16       * wait () method releases the lock, thus once the call wait () method will cause the other threads to run
 . 17       * / 
18 is      public  the synchronized  void waitMethod ( ) {
 . 19          System.out.println ( "Start the Wait:" + Thread.currentThread (). getName ());
 20 is          the try {
 21 is              the wait (1000 );
 22 is          } the catch (InterruptedException E) {
 23 is              e.printStackTrace ();
 24          }
 25          
26 is          System.out.println ( "End the Wait:" +Thread.currentThread () getName ());.
 27      }
 28  
29      public  static  void main (String [] args) {
 30          Final SleepTest test1 = new new SleepTest ();
 31 is          for ( int I = 0; I <. 5; I ++ ) {
 32              new new the Thread (() -> test1.sleepMethod ()) Start ();.
 33 is          }
 34 is  
35          the try {
 36              // pause ten seconds, and so execution is completed above 
37 [              the Thread.sleep (10000 );
 38 is          } the catch ( InterruptedException e) {
39             e.printStackTrace();
40         }
41 
42         System.out.println("-----分割线-----");
43 
44         final SleepTest test2 = new SleepTest();
45         for (int i = 0; i < 5; i++) {
46             new Thread(() -> test2.waitMethod()).start();
47         }
48     }
49 }

sleep is a complete implementation of a first start and then end, from this phenomenon glance sleep () method does not release the lock; while the wait will not hand over executive power of the CPU.

If synchronize deleted 18 lines, wait () method will throw IllegalMonitorStateException exception, so wait () method must be performed synchronize block.

wait():

1, wait () \ notify ( ) method usually come in pairs

2, wait () \ notify ( ) methods need to be performed in block synchronize

3, wait () methods () method interrupt interrupted by the suspend state

4, through to wait () method to set the time (wait (1000)) or call the notify () method allows objects to re-acquire the lock

notify()/notifyAll():

1, notify () wait for the user on a single thread wake-up object, notifyAll () a plurality of threads wakeup

2, notifyAll () order is advanced after wake-up, Last In First Out

. 3, the wait () / Notify () / notifyAll () relates to the communication between threads

 1 public class WaitClassDemo {
 2 
 3     private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
 4 
 5     public static void main(String[] args) {
 6         Object obj = new Object();
 7         for (int i = 0; i < 5; i++) {
 8             new WaitThread(i + "", obj).start();
 9         }
10         new NotifyThread(obj).start();
11     }
12 
13     /**
14      * 调用wait()方法的线程
15      */
16     static class WaitThread extends Thread {
17         Object obj;
18         public WaitThread(String name, Object obj) {
19             setName("WaitThread" + name);
20             this.obj = obj;
21         }
22 
23         @Override
24         public void run() {
25             synchronized (obj) {
26                 System.out.println(sdf.format(new Date()) + " " + getName() + " before wait()");
27                 try {
28                     obj.wait();
29                 } catch (InterruptedException e) {
30                     e.printStackTrace();
31                 }
32                 System.out.println(sdf.format(new Date()) + " " + getName() + " after wait()");
33             }
34         }
35     }
36 
37     /**
38      * 调用notify()/notifyAll()
39      */
40     static class NotifyThread extends Thread {
41         Object obj;
42         public NotifyThread(Object obj) {
43             setName("NotifyThread");
44             this.obj = obj;
45         }
46 
47         @Override
48         public void run() {
49             synchronized (obj) {
50                 try {
51                     Thread.sleep(5000);
52                 } catch (InterruptedException e) {
53                     e.printStackTrace ();
 54 is                  }
 55                  System.out.println (sdf.format ( new new a Date ()) + "Notify before NotifyThread ()" );
 56 is                  // wake up all threads using notifyAll () will follow the LIFO ( LIFO) sequence resume the thread 
57 is                  obj.notifyAll ();
 58                  the try {
 59                      the Thread.sleep (5000 );
 60                  } the catch (InterruptedException E) {
 61 is                      e.printStackTrace ();
 62 is                  }
 63 is                  System.out.println (SDF. format ( new new Date()) + " NotifyThread after notify()");
64             }
65         }
66     }
67 }

yieId ():

1. Role: CPU tell you this and give me the resources I do not, you go to the other threads it (¯)¯) ↗

2, note that:

) YieId () method does not ensure that other threads will be able to perform, because it is still executable state, the CPU may still be executed again

) Execution yieId () method does not release the lock

join():

1, effect: make a thread execution in another thread after their execution

2. Note: The internal execution thread A thread B join () method, then A will block until the thread B will be performed after the implementation of thread A

3, Demo: Xiao Ming ordered a pancake fruit, the boss after receipt of order began to do pancakes; that Bob is certainly not impossible to do what matter before the fruit to pancakes, the boss is the same; here we use threads to achieve them two movements.

. 1  public  class Consumer {
 2  
. 3      public  void EAT () {
 . 4          System.err.println ( "Start pancakes fruit ..." );
 . 5          the try {
 . 6              the Thread.sleep (1000 );
 . 7          } the catch (InterruptedException E) {
 . 8              e.printStackTrace ();
 . 9          }
 10          System.err.println ( "pancake fruit eating it ..." );
 11      }
 12 }
. 1  public  class Producer {
 2  
. 3      public  void Manufacture () {
 . 4          System.out.println ( "start making pancake fruit ..." );
 . 5          the try {
 . 6              the Thread.sleep (1000 );
 . 7          } the catch (InterruptedException E) {
 . 8              e.printStackTrace ();
 . 9          }
 10          System.out.println ( "pancake finished fruit ..." );
 11      }
 12 }
 1 public class JoinTest {
 2 
 3     public static void main(String[] args) {
 4         Thread producerThread = new Thread(() -> {
 5             Producer producer = new Producer();
 6             producer.manufacture();
 7         });
 8         producerThread.start();
 9 
10         Thread consumerThread = new Thread(() -> {
11             try {
12                 producerThread.join();
13             } catch (InterruptedException e) {
14                 e.printStackTrace();
15             }
16             Consumer consumer = new Consumer();
17             consumer.eat();
18         });
19         consumerThread.start();
20     }
21 }

to sum up:

1, method calls: sleep (), yieId () is a static method of the Thread class; the Join () is an exemplary method of the Thread class; wait (), notify (), notifyAll () method is an example of class Object

2, release the lock: Thread.sleep (), Thread.yieId () does not release the lock; wait () releases the locks

3, execution location: sleep (), yieId () , join () does not necessarily need to be performed synchronize block; wait (), notify () , notifyAll () needs to be performed synchronize block, otherwise it will throw IllegalMonitorStateException

 

 

Guess you like

Origin www.cnblogs.com/bzfsdr/p/11568253.html