多程,互需锁不释放
同时
窗口1:先object锁,再this锁,票数-1
窗口2:先this锁,再object锁,票数-1
public class TickerThread3 implements Runnable {
private static int count=100;
private Boolean flag=true;
private Object object=new Object();
@Override
public void run() {
if(flag){
while (count>0){
synchronized (object){
try {
Thread.sleep(10);
}catch (Exception e)
{
}
ticket();
}
}
}else {
while (count>0){
ticket();
}
}
}
public synchronized void ticket(){
synchronized (object){
try {
Thread.sleep(10);
}catch (Exception e)
{
}
}
if(count>0){
System.out.println(Thread.currentThread().getName()+",正在出票第【"+(100-count+1)+"】张");
count--;
}
}
public static void main(String arg[])
{
TickerThread3 tickerThread=new TickerThread3();
new Thread(tickerThread,"售票机1号").start();
try {
Thread.sleep(40);
tickerThread.flag=false;
}catch (Exception e)
{
}
new Thread(tickerThread,"售票机2号").start();
}
}