selling tickets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class SellThread implements Runnable
{
private int ticketCount = 10;// total tickets, all thread will visit
Object mutex = new Object();// mutex
/**
* selling ticket
*/
public void sellTicket()
{
synchronized (mutex)
{
if (ticketCount > 0)
{
ticketCount--;
System.out.println(Thread.currentThread().getName()
+ "selling..." + ticketCount + "tickets left");
}
else
{
System.out.println("sell done!");
return;
}
}
}
public void run()
{
while (ticketCount > 0)
{
sellTicket();
//sleep 1 millisecond so that each thread
//has the chance to sell ticket
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Test{
public static void main(String[] args)
{
SellThread runTicekt = new SellThread();//one instance will lead to only one object
//,so we have only one mutex
Thread th1 = new Thread(runTicekt, "window1");
Thread th2 = new Thread(runTicekt, "window2");
Thread th3 = new Thread(runTicekt, "window3");
Thread th4 = new Thread(runTicekt, "window4");
th1.start();
th2.start();
th3.start();
th4.start();
try{
th4.join();
th3.join();
th2.join();
th1.join();
}catch (Exception e){
e.printStackTrace();
}
}
}