- public static void main(String[] args) {
-
- new TicketsSeller().start();
- new TicketsSeller().start();
- new TicketsSeller().start();
- new TicketsSeller().start();
- }
- }
- class TicketsSeller extends Thread {
- private static int tickets = 100;
- private static Object obj = new Object();
- public void run() {
- while(true) {
- synchronized(obj) {
- if(tickets == 0)
- break;
- try {
- Thread.sleep(10); //使运行结果更加符合实际情况
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(getName() + "...这是第" + tickets-- + "号票");
- }
- }
- }
- }
复制代码
|
|