62,614
社区成员
发帖
与我相关
我的任务
分享
public class ThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),"线程1");
Thread t2 = new Thread(new MyRunnable(),"线程2");
t1.start();
t2.start();
}
}
public class MyRunnable implements Runnable {
public static int ticket = 300;
Object lock = new Object();
static String preName;
static String newName;
boolean flag = true;
@Override
public void run() {
while (true) {
synchronized (lock) {
if (ticket > 0) {
if (flag) {
preName = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName() + "正在卖第" + (ticket--) + "张票");
flag = false;
continue;
}
newName = Thread.currentThread().getName();
if (newName.equals(preName)) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + "正在卖第" + (ticket--) + "张票");
preName = newName;
lock.notify();
}
}
}
if (ticket == 0) {
break;
}
}
}
}