package com.jacob.activeX;
import java.util.concurrent.TimeUnit;
public class Test implements Runnable {
int ticket = 20;// 票号
public static void main(String[] args) {
Test a = new Test();
// 同时启动三个线程
Thread thread = new Thread(a);
thread.setName("1号窗口");
thread.start();
Thread thread2 = new Thread(a);
thread2.setName("2号窗口");
thread2.start();
Thread thread3 = new Thread(a);
thread3.setName("3号窗口");
thread3.start();
}
public void run() {
while (true) {
// 加入线程锁保证线程安全 synchronized(Object){
synchronized (this) {
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + i++);
}
if (ticket > 0) {
System.out.println(Thread.currentThread().getName()
+ ":当前票是" + ticket);
ticket--; // 票号--
} else {
break;
}
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}