【复习笔记】手写生产者消费者 & 死锁

看到几次有面经谈到死锁跟生产消费者模型的手写代码了,手动撸一份复习一下:

生产者消费者:

import java.util.ArrayList;

public class proAndCus {

	public static void main(String[] args) {
		final box bigbox = new box();
		for (int i = 0; i < 500; ++i) {
			new Thread(new Runnable() {
				public void run() {
					produ pro = new produ(bigbox);
					pro.put();
				}
			}).start();
		}
		for (int i = 0; i < 500; ++i) {
			new Thread(new Runnable() {
				public void run() {
					cust cus = new cust(bigbox);
					cus.get();
				}
			}).start();
		}
	}
}

class box {
	static ArrayList<apple> boxlist = new ArrayList<apple>();
	static int capacity = 50;

	public void put(apple app) {
		synchronized (this) {
			try {
				while (boxlist.size() >= capacity)
					wait();
				boxlist.add(app);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			notifyAll();
			System.out.println("put finished! Now the box has "
					+ boxlist.size() + " apples!");
		}
	}

	public apple get() {
		apple res = null;
		synchronized (this) {
			try {
				while (boxlist.size() <= 0)
					wait();
				res = boxlist.remove(boxlist.size() - 1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			notifyAll();
			System.out.println("get finished! Now the box has "
					+ boxlist.size() + " apples!");
		}
		return res;
	}
}

class apple {
	private String name = "我是可爱的小苹果";
}

class produ {
	private box mybox;

	produ(box b) {
		this.mybox = b;
	}

	public void put() {
		apple app = new apple();
		mybox.put(app);
	}
}

class cust {
	private box mybox;

	cust(box b) {
		this.mybox = b;
	}

	public apple get() {
		return mybox.get();
	}
}

死锁:

public class deadLock {

	public static void main(String[] args) {
		Object o1 = new Object();
		Object o2 = new Object();
		new Thread(new thr(o1,o2,1)).start();
		new Thread(new thr(o1,o2,2)).start();
	}
}

class thr implements Runnable{
	Object o1;
	Object o2;
	int num;
	public thr(Object o1, Object o2, int num){
		this.o1 = o1;
		this.o2 = o2;
		this.num = num;
	}
	
	public void run(){
		if(num == 1){
			synchronized(o1){
				try{
					Thread.sleep(100);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				synchronized(o2){
					System.out.println("thread 1 finished");
				}
			}
		}
		if(num == 2){
			synchronized(o2){
				try{
					Thread.sleep(100);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
				
				synchronized(o1){
					System.out.println("thread 2 finished");
				}
			}
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值