JAVA_Thread_deadlock
4395 ワード
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--;
}
}
}
}
}