JAvaマルチスレッド実現チケット販売ウィジェット
9414 ワード
1 package shb.java.demo;
2 /**
3 * 。
4 * @Package:shb.java.demo
5 * @Description:
6 * @author shaobn
7 * @Date 2015-9-2 7:49:53
8 */
9 public class TestSyn {
10 public static void main(String[] args) {
11 //
12 /*TicketDemo td = new TicketDemo();
13 Thread t1 = new Thread(td);
14 Thread t2 = new Thread(td);
15 t1.start();
16 t2.start();*/
17 //
18 TicketDemo2 td2 = new TicketDemo2();
19 Thread t3 = new Thread(td2);
20 Thread t4 = new Thread(td2);
21 t3.start();
22 t4.start();
23 }
24 }
25 /**
26 * ( )
27 * @Package:shb.java.demo
28 * @Description:
29 * @author shaobn
30 * @Date 2015-9-2 7:44:45
31 */
32 class TicketDemo implements Runnable{
33 private int ticket = 200;
34 public void run(){
35 while(true){
36 synchronized(this){
37 if(ticket>0){
38 try {
39 Thread.sleep(100);
40 } catch (Exception e) {
41 // TODO: handle exception
42 e.printStackTrace();
43 }
44 System.out.println(Thread.currentThread()+"***"+" "+ticket--);
45 }
46 }
47 }
48 }
49
50 }
51 /**
52 * ( )
53 * @Package:shb.java.demo
54 * @Description:
55 * @author Shihaobin
56 * @Date 2015-9-2 7:51:56
57 */
58 class TicketDemo2 implements Runnable{
59 public int ticket = 200;
60 public void run(){
61 while(true){
62 show();
63 }
64 }
65 //
66 public synchronized void show(){
67 if(ticket>0){
68 try {
69 Thread.sleep(100);
70 } catch (Exception e) {
71 // TODO: handle exception
72 e.printStackTrace();
73 }
74 System.out.println(Thread.currentThread()+"***"+" "+ticket--);
75 }
76
77 }
78 }
。
転載先:https://www.cnblogs.com/assassin666/p/4779359.html