public class CopyOfThreadSafeTest implements Runnable {
int num = 10; // 定义总票数
public void run() {
while (true) {
synchronized ("") { // 定义同步块
if (num > 0) { // 如果总票数大于0
try {
Thread.sleep(1000); // 线程休眠
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("剩余票数为:" + --num); // 输出提示信息
}
}
}
}
public static void main(String[] args) {
CopyOfThreadSafeTest t = new CopyOfThreadSafeTest(); // 定义本类对象
Thread tA = new Thread(t); // 定义线程对象
Thread tB = new Thread(t);
Thread tC = new Thread(t);
Thread tD = new Thread(t);
tA.start(); // 驱动线程
tB.start();
tC.start();
tD.start();
}
}
|