1. 程式人生 > 其它 >使用同步程式碼塊 synchronized 解決買票問題

使用同步程式碼塊 synchronized 解決買票問題

package com.bo.myThread.Demo02;

public class Demo implements Runnable {
//100張票
private int t=100;
private Object obj=new Object();
@Override
public void run() {

while(t>=0){
synchronized (obj){//同步程式碼塊 裡面不能直接new Object 因為obj只有一份
if (t<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"出售了第"+t+"張票");
t--;
}
}
}
}




package com.bo.myThread.Demo02;

public class TextDemo {
public static void main(String[] args) {
Demo demo=new Demo();
//Runnable demo=new Runnable() {
int t = 100;
//public void run() {

//while (true) {
// if (t <= 0) {
// break;
// }
// System.out.println(Thread.currentThread().getName()+"出售了第"+t+"張票");
// t--;
// }
// }


//};
Thread t1 =new Thread(demo,"視窗1");
Thread t2 =new Thread(demo,"視窗2");
Thread t3 =new Thread(demo,"視窗3");
Thread t4 =new Thread(demo,"視窗4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}