生产消费者


package com.ztianyi.test;

/**
 * 
 * @author tianji_zhou
 *
 * 缓冲区为5的生产者 消费者协同
 * <p>1.System.out.下面的方法不是线程安全的
 * <p>2.wait(),notify(),notifyAll()必须在同步方法中
 * <p>3.wait()方法最好是在while里面而不是if
 */
public class MultiThreadTest {
 
 int i = 0;
 
 synchronized public void sub()
 {
  while(this.i<1)//if->while 被唤醒的时候需要重新判断
  {
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  
  System.out.print(MultiThreadTest.this.i);
  i--;
  System.out.println("-1="+MultiThreadTest.this.i);
  this.notifyAll();
 }
 
 synchronized public void add(){
 
  while(this.i>4)//if->while 被唤醒的时候需要重新判断
  {
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }

  System.out.print(MultiThreadTest.this.i);
  i++;
  System.out.println("+1="+MultiThreadTest.this.i);
  this.notifyAll();
 }
 
 public class SubWorker implements Runnable
 {
  public void run(){
   for(int i=0; i<1000; i++)
   {
    sub();
   }
  }
 }
 
 public class AddWorker implements Runnable
 {
  public void run()
  {
   for(int i=0; i<500; i++)
   {
    add();
   }
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  MultiThreadTest test = new MultiThreadTest();
  
  SubWorker subWorker =  test.new SubWorker();
  AddWorker addWorker = test.new AddWorker();
  
  Thread sub = new Thread(subWorker);
  Thread add1 = new Thread(addWorker);
  Thread add2 = new Thread(addWorker);
  sub.start();
  add1.start();
  add2.start();

 }

}

 


你可能感兴趣的:(多线程,同步)