Java thread notes - producers and consumers

Java thread notes

1. Introduction thread:

  Each object in Java can be used as a lock, which is synchronized to achieve synchronization of the foundation;

  • Normal synchronization method (method of example), the lock is the current instance of the object, before entering the synchronization code to obtain the current instance of the lock;
  • Static synchronization method, the lock current class is an object class, before entering the synchronization code to obtain the current locks the object;
  • Block synchronization method, the object lock is inside the brackets, to lock a given object, before entering the synchronization code library to obtain a given lock of the object;

 

2. synchronized keyword;

  Keywords can be synchronized to ensure at the same time, only one thread can execute a method or a block of code; for multiple threads to solve the problem of co-operation to share data.

 

3. The method of introduction;

  • wait (): the current thread into a wait state, release the lock, stop executing wait () method behind the statement;
  • notify() : 
  • notifyAll (): After notify all waiting threads same resources, will not release the lock immediately after the implementation of the current thread releases the lock, that is, notifyAll () notice is required after the implementation of the current thread releases the lock, other threads waiting to grab to resources;

 

4. producer - consumer implementation of a (synchronized, wait and notify)

4.1 to define a resource pool, the method to store threads share resources and provide production and consumption of resources for

1  // define a resource pool based the Resource 
2  
. 3  class the Resource {
 . 4      Private  int NUM = 0 ;
 . 5      Private  int size = 10 ;
 . 6  
. 7      // get resources from the resource pool 
. 8      public  the synchronized  void Remove () {
 . 9          IF ( NUM> 0 ) {
 10              num-- ;
 11              . System.out.println ( "consumer" + Thread.currentThread () getName () + " consumption of a resource," + "current thread pool has" + num + " a " );
 12              // after the current sync block of statements does not release the lock before executing the continued implementation of the latter to release the lock, so inform wake up waiting threads, other threads can not be executed immediately;
13 is              notifyAll (); 
 14          } the else {
 15              the try {
 16                  System.out.println (. "Consumers" + Thread.currentThread () getName () + " thread enters Start [enter] wait state" );
 . 17                  // the wait release the lock, stop continues until they were awakened before continuing down the implementation of
 18                  // If there is no resource, the consumer enters a wait state 
19                  the wait (); 
 20                  System.out.println ( "consumer" + Thread.currentThread (). getName () + "thread [end] wait state" );
 21 is              } the catch (InterruptedException E) {
 22 is                  // the TODO Auto-Generated Block the catch 
23 is                 e.printStackTrace ();
 24              }
 25          }
 26 is      }
 27  
28      // to add a resource in the resource pool 
29      public  the synchronized  void the Add () {
 30          IF (NUM < size) {
 31 is              NUM ++ ;
 32              System.out.println (the Thread. . currentThread () getName () + " production of a resource, the current resource pool has" + num + "a" );
 33              // notify all are waiting in the queue waiting for the same shared resource "all thread" to exit the queue waiting to enter runnable state
 34 is              // Notify not release the lock, must complete execution notify () synchronized code block where the method of release after 
35              notifyAll (); 
 36             the try {
 37 [                  the Thread.sleep (5000 );
 38 is              } the catch (InterruptedException E) {
 39                  // the TODO Auto-Generated Block the catch 
40                  e.printStackTrace ();
 41 is              }
 42 is          } the else {
 43 is              the try {
 44 is                  the wait (); // producers of the current thread enters a wait state and release the lock 
45                  System.out.println (Thread.currentThread () getName () + "thread enters a wait." );
 46 is              } the catch (InterruptedException E) {
 47                 // TODO Auto-generated catch block
48                 e.printStackTrace();
49             }
50 
51         }
52     }
53 }

4.2 Defining producer

// definition of producer thread 

/ * 
 * producer thread 
 * / 
class ProducerThread the extends the Thread {
     Private the Resource Resource; 

    public ProducerThread (the Resource Resource) {
         Super ();
         the this .resource = Resource; 
    } 

    public  void RUN () {
         // continue produced resources 
        the while ( to true ) {
             the try { 
                the Thread.sleep ( 8000 ); 
            } the catch (InterruptedException E) {
                 // TODO Auto-generated catch block
                e.printStackTrace();
            }
            resource.add();
        }
    }
}

4.3 the definition of consumer

// definition of consumer thread 

/ * 
 * consumer thread 
 * / 
class a ConsumerThread the extends the Thread {
     Private the Resource Resource; 

    public a ConsumerThread (the Resource Resource) {
         Super ();
         the this .resource = Resource; 
    } 

    public  void RUN () {
         the while ( to true ) {
             the try { 
                the Thread.sleep ( 3000 ); 
            } the catch (InterruptedException E) {
                 // the TODO Auto Block the catch-Generated
                e.printStackTrace();
            }
            resource.remove();
        }
    }
}

4.4 Test main class definitions

 1 public class ProducerConsumerWithWaitNofity {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         Resource resource = new Resource();
 6         //生产者线程
 7         ProducerThread p1 = new ProducerThread(resource);
 8 //        ProducerThread p2 = new ProducerThread(resource);
 9 //        ProducerThread p3 = new ProducerThread(resource);
10         
11         //消费者线程
12         ConsumerThread c1 = new ConsumerThread(resource);
13         ConsumerThread c2 = new ConsumerThread(resource);
14         
15         p1.start();
16 //        p2.start();
17 //        p3.start();
18         c1.start();
19         c2.start();
20     }
21 
22 }

 

 

 

 

Note: Code Case Reprinted from: https: //www.cnblogs.com/xiaowenboke/p/10469125.html

 

Guess you like

Origin www.cnblogs.com/crazytrip/p/11861765.html