练手java thread(一)

生产者和消费者模型:

 

package thread;

class Producer implements Runnable {
	public Producer(Q q) {
		this.q = q;
	}

	Q q;

	public void run() {
		int i = 0;
		while (true) {
			/*
			synchronized (q) {// 当前线程得到对象q的lock旗标
				if (q.bFull) {
					try {
						q.wait();// 此时当前线程被放置在对象q的等待池中,当前线程释放q的锁旗标
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				if (i == 0) {
					q.name = "zhangsan";
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					q.sex = "male";
				} else {
					q.name = "lisi";
					q.sex = "female";
				}
				q.bFull = true;
				q.notify();// 当另外的线程执行了对象o的notify()方法后,当前线程可能会被从q的等待
				// 线程池中释放出来,并且移动到等待线程对象q的锁旗标的线程池中,当当前 //线程得到的锁旗标时就会执行下去
			}*/

			if (i == 0) {
				q.put("zhangsan", "male");
			} else {
				q.put("lisi", "female");
			}
			i = (i + 1) % 2;
		}

	}
}

class Consumer implements Runnable {
	public Consumer(Q q) {
		this.q = q;
	}

	Q q;

	@Override
	public void run() {
		while (true) {
			/*
			 * synchronized (q) { 
			 *     if (!q.bFull) { 
				       try { 
				           q.wait(); 
				       } catch(InterruptedException e) { 
				           e.printStackTrace(); 
				       } 
			 *     } 
			 *     if (q.name != "") { 
			 *         System.out.print(q.name); q.name = ""; 
			 *     } 
			 *     if (q.sex != "") {
			 *         System.out.println(":" + q.sex); q.sex = ""; 
			 *     } 
			 *     q.bFull = false;
			 *     q.notify(); }
			 */
			q.get();
		}

	}
}

class Q {
	private String name = "unknown";
	private String sex = "unknown";
	private boolean bFull = false;

	public synchronized void put(String name, String sex) {
		if (bFull) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.name = name;
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.sex = sex;
		bFull = true;
		notify();
	}

	public synchronized void get() {
		if (!bFull) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.print(name);
		System.out.println(":" + sex);
		bFull = false;
		notify();
	}

}

 

 

调用入口:

 

public class ThreadCommunation {
	public static void main(String[] args) {
		
		Q q = new Q(); 
		new Thread(new Producer(q)).start(); 
		new Thread(new Consumer(q)).start();
		
         }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值