如果不加synchronized()同步锁,则会出现两个窗口卖了一张票
多线程的类
代码如下
public class SellTicktDemo implements Runnable {
//定义总票数
private int total =100;
//定义编号
private int no = total+1;
//定义线程同步对象
private Object object = new Object();
@Override
public void run() {
while (true) {
//同步锁
synchronized (this.object) {
//如果当前票数大于0了才可以卖
if (this.total > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
String msg = Thread.currentThread().getName() + "售出第" + (this.no - this