package threadDemo;
public class ThreadDemo03 {
public static void main(String[] args) {
T t = new T();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
t.flag=false;
t2.start();
}
}
class T implements Runnable {
private int ticket = 100;
boolean flag = true;
Object obj = new Object();
@Override
public void run() {
if (flag) {
while (true) {
//synchronized (this) {
synchronized (obj){
if (ticket > 0) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket-- + "张票");
}
}
}
}else{
while(true){
show();
}
}
}
public synchronized void show(){//synchronized (this)
if (ticket > 0) {
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket-- + "张票");
}
}
}