java 多线程同步/ 消费者生产者问题.
多线程下要注意的地方:
1. this.wait()和this.notify()要成对使用;
2. 对于sychronized要慎重. 上锁/不上锁要谨慎考虑. 用了可能会在效率上下降, 不用可能导致不可预测的结果值.
3. wait 和 thread.sleep()有很大差别: wait是object类中的方法, 而sleep是thread下的方法. wait表示指的是当前的线程进行wait...
而sleep是认为的控制等待等待多少时间后再执行.
4. 线程创建有两种方法
1: class mythread implements Runnable{
public void run(){
..... .
}
}
mythread mt = new mythread ();
Thread t = new Thread(mt);
t.start();
2. 从Thread继承
class mythread extends Thread {
public void run() {
..... .
}
}
}
mythread mt = new mythread ();
mt.start();
以蒸窝窝头为例:消费者生产者代码:
public class ProducerConsumer{ public static void main( String args[] ){ SynStack ss = new SynStack(); Producer p = new Producer(ss); Consumer c = new Consumer(ss); Thread t = new Thread(p); Thread t2 = new Thread(c); t.start(); t2.start(); } } class WoTou{ int id; WoTou( int _id ){ id = _id; } public String toString(){ return id; } } class SynStack{ WoTou[] arrWoTou = new WoTou[6];//蒸笼大小为6
private int idx = 0; public synchronized void push( WoTou wt ){ //if( idx == arrWoTou.length) { //用if如果出现了 中断错误, 那么会跳出if体. 也会出错, 所以用while
while( idx == arrWoTou.length ){ try{ System.out.println("to many wotou.. please wait ```"); this.wait(); //
}catch( InterruptedException e ){ e.printStackTrace(); } } arrWoTou[idx++] = wt; this.notify();//被所定的对象上 , 通知他们..当前这个进程上有哪个在等待对应的信息,叫醒他们.
} public synchronized WoTou pop(){ //if( idx == 0 ) { while( idx == arrWoTou.length ){ try{ System.out.println("no wotou.. please wait ```"); this.wait(); // 指的是当前的线程进行wait...
}catch( InterruptedException e ){ e.printStackTrace(); } } this.notify(); return arrWoTou[--idx]; } } class Producer implements Runnable{ SynStack ss = null; Producer( SynStack _ss ){ ss = _ss; } public void run(){ for( int i = 0; i < 20; i++ ){ WoTou wt = new WoTou(i); System.out.println("produce : " + wt); ss.push(wt); try{ Thread.sleep(3000); } catch( InterruptedException e ){ e.printStackTrace(); } } } } class Consumer implements Runnable{ SynStack ss = null; Consumer( SynStack _ss ){ ss = _ss; } public void run(){ for( int i = 0; i < 20; i++ ){ WoTou wt = new WoTou(i); System.out.println("consume : " + wt); ss.pop(); System.out.println(wt); try{ Thread.sleep(1000); } catch( InterruptedException e ){ e.printStackTrace(); } } } }
可以改变下代码中的 wait, notify等... 来看下其作用..
*******************************
***** Never ever let you down. *****
*******************************