51,411
社区成员
发帖
与我相关
我的任务
分享
//Runnable的实现类对象
public class RunnableImpl implements Runnable {
private int ticket = 100;//票的张数
@Override
public void run() {
while (true) {
synchronized (this) {//使用线程锁,这里是一个同步代码块,用于解决线程安全问题
if (ticket > 0) {
try {//因为sleep有异常这里用try...catch解决异常
Thread.sleep(10);//让程序休眠10毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
ticket--;
} else
break;
}
}
}
}
//运行的类
public class RunnableMain {
public static void main(String[] args) {
RunnableImpl run = new RunnableImpl();//创建实现类对象
Thread t0 = new Thread(run);
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t0.start();//开启多线程
t1.start();
t2.start();
}
}

把休眠时间调大一点应该也行