JAVA_Thread_deadlock

package com.kk.thread;
/*
* 本类演示死锁的形成
* 基本数据类型是不能作为同步块的参考,例:int b;synchronized(b)
*/
public class TicketsSystem {

public static void main(String[] args)throws Exception {
SellThread sell=new SellThread();
new Thread(sell).start();
Thread.sleep(1);//让thread1执行,此时b=false;
sell.b=true;
new Thread(sell).start();
}

}

class SellThread implements Runnable{

int tickets=1000;
Object obj=new Object();
boolean b=false;
public void run() {
if (b) {
sell();
}else{
synchronized(obj){ //将obj锁住
while(true){
if (tickets>0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(this){ //按照本程序的执行顺序,此时this已经被sell方法锁住
System.out.println("obj___"+Thread.currentThread().getName()+"__"+tickets);
tickets--;
}
}
}
}
}
}

/*
* 同步方法会给类的实例加锁(this)
* 静态同步方法会给类加锁(Class)
*/
private synchronized void sell(){ //将类的实例锁住(this)
while(true){
if (tickets>0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(obj){ //等线程苏醒,obj已经被run方法中的synchronized(obj)锁住
System.out.println("this___"+Thread.currentThread().getName()+"__"+tickets);
tickets--;
}
}
}
}

}

你可能感兴趣的:(thread)