首先,创建SellTickets类 实现接口Runnable,重写run方法,代码展示如下:
public class SellTickes implements Runnable {
private int tickes = 100;
Object obj = new Object();
@Override
public void run() {
while(true) {
synchronized (obj) { //同步代码块结束数据安全问题
if(tickes>0) {
System.out.println(Thread.currentThread().getName()+"正在售卖第"+tickes+"张票");
tickes--;
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
然后,创建多个线程售票,代码如下:
public class test {
public static void main(String[] args) {
SellTickes t = new SellTickes();
Thread t1 = new Thread(t,"1");
Thread t2 = new Thread(t,"2");
Thread t3 = new Thread(t,"3");
t1.start();
t