01 | class LockDemo{ |
02 | public static void main(String [] hello){ |
03 | TestThread tt = TestThread.getInstance_robot(); |
04 | new Thread(tt).start(); //on work ,here comes a client saler A |
05 | try {Thread.sleep( 10 );} catch (Exception e){} |
06 | |
07 | tt.lockname = "Vip_clinet1" ; //saler B was late for work,but |
08 | //later is better than never |
09 | new Thread(tt).start(); |
10 | } |
11 | } |
12 | |
13 | class TestThread implements Runnable{ |
14 | |
15 | private int how_many; //counter |
16 | private static TestThread FC_instance = null ; |
17 | |
18 | //singleton it~ |
19 | private TestThread(){ |
20 | this .how_many = 0 ; |
21 | } |
22 | |
23 | public static TestThread getInstance_robot(){ |
24 | if (FC_instance == null ) |
25 | return new TestThread(); |
26 | return FC_instance; |
27 | } |
28 | |
29 | String lockname = "iamalock hahahaha~" ; |
30 | int tickets = 1200 ; //assume there is 1200 |
31 | //railway ticket waiting to get saled by |
32 | //2 operators in the station's terminal windows |
33 | |
34 | public void run(){ |
35 | |
36 | int tickets_flag = this .tickets; |
37 | |
38 | if (lockname.equals( "Vip_clinet1" )) |
39 | { |
40 | while ( true ){ |
41 | if (tickets > 0 ){ |
42 | try {Thread.sleep( 1 );} /**VIP嘛 当然要慢那么一点点了哦..*/ catch (Exception e){} |
43 | synchronized (lockname){}; |
44 | System.out.println( "| " + this .lockname+ " is saling ticket: " +tickets--+ " | " ); |
45 | } |
46 | } |
47 | } else //anoymous robot saler -_-*) |
48 | { |
49 | while ( true ){ //我要风了,,,还是处理不好CPU时间片儿的问题阿 |
50 | synchronized (lockname){ |
51 | if (tickets > 0 ){ |
52 | try {Thread.sleep( 3 );} catch (Exception e){} |
53 | synchronized (lockname){}; |
54 | System.out.println( "\t\t\t\t\t | " +Thread.currentThread().toString()+ " is saling tickets " +tickets--+ " | " ); |
55 | how_many++; |
56 | } else |
57 | { |
58 | System.out.println(tickets_flag+ "张票 全部受完\t打烊!" ); |
59 | System.out.println( "报告长官:VIP售出" +(tickets_flag-how_many)+ " 张票\n" ); |
60 | System.out.println( "机器人员工售出:" +how_many+ "张票\n" ); |
61 | |
62 | //try{Thread.stop(this);}catch(Exception e){} |
63 | return ; |
64 | } |
65 | } |
66 | } |
67 | } |
68 | |
69 | } //end function run() |
70 |
|