public class ThreadSellticketDemo {
public static void main(String[] args) {
MyRunnable m1 = new MyRunnable();
Thread t1 = new Thread(m1,"窗口1");
Thread t2 = new Thread(m1,"窗口2");
Thread t3 = new Thread(m1,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable{
private int tickets=100;
private Object obj = new Object();
public void run() {
while(true){
if(tickets==0){
throw new RuntimeException("没有电影票了");
}
synchronized(obj){
if(tickets>0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖"+
(tickets--)+"张电影票");
}
}
}
}
}
public static void main(String[] args) {
MyRunnable m1 = new MyRunnable();
Thread t1 = new Thread(m1,"窗口1");
Thread t2 = new Thread(m1,"窗口2");
Thread t3 = new Thread(m1,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
class MyRunnable implements Runnable{
private int tickets=100;
private Object obj = new Object();
public void run() {
while(true){
if(tickets==0){
throw new RuntimeException("没有电影票了");
}
synchronized(obj){
if(tickets>0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖"+
(tickets--)+"张电影票");
}
}
}
}
}