看到几次有面经谈到死锁跟生产消费者模型的手写代码了,手动撸一份复习一下:
生产者消费者:
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");
}
}
}
}
}