チケット購入問題-スレッドの同期
5524 ワード
1 //
2 package ThreadL;
3
4 public class Thread9 {
5 public static void main(String[] args){
6 Thread th1 = new Thread(new Thread9L(),"AAA");
7 Thread th2 = new Thread(new Thread9L(),"BBBBBB");
8 th1.start();
9 th2.start();
10 }
11 }
12 class Thread9L implements Runnable{
13 static int ticket = 100;
14 static int count = 0;
15 public void run(){
16 while(true){
17 synchronized("L") //
18 {
19 if(ticket>0){
20 /* try {
21 Thread.sleep(1000);
22 } catch (InterruptedException e) {
23 // TODO Auto-generated catch block
24 e.printStackTrace();
25 }
26 */ System.out.println(Thread.currentThread().getName() + "\t \t" + ticket-- + "\t 。");
27 count++;
28 }else{
29 System.out.println(Thread.currentThread().getName() + "\t 。\t" + count);
30 break;
31 }
32 }
33 }
34 }
35 }