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等... 来看下其作用..

转载于:https://www.cnblogs.com/25-to-life/archive/2010/08/21/1805479.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值