class Ticket implements Runnable{
private int ticket=100;
Object obj=new Object();
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized(obj){
if(ticket>0){
try {Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"--->"+ticket--);
}
}
}
}
}
public class TestTicket {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
结果如下:
Thread-2--->100
Thread-0--->99
Thread-1--->98
Thread-3--->97
Thread-2--->96
Thread-0--->95
Thread-1--->94
Thread-3--->93
Thread-2--->92
Thread-0--->91
Thread-1--->90
Thread-3--->89
Thread-1--->88
Thread-3--->85
Thread-0--->86
Thread-2--->87
Thread-0--->84
Thread-2--->83
Thread-3--->84
Thread-1--->82
Thread-3--->81
Thread-0--->80
Thread-2--->79
Thread-1--->78
Thread-2--->77
Thread-3--->76
Thread-1--->75
Thread-0--->77
Thread-3--->74
Thread-1--->73
Thread-2--->72
Thread-0--->71
Thread-1--->70
Thread-2--->69
Thread-3--->68
Thread-0--->67
Thread-0--->66
Thread-1--->65
Thread-3--->64
Thread-2--->63
Thread-0--->62
Thread-3--->61
Thread-2--->59
Thread-1--->60
Thread-1--->58
Thread-2--->57
Thread-3--->56
Thread-0--->55
Thread-1--->54
Thread-2--->53
Thread-0--->52
Thread-3--->51
Thread-1--->50
Thread-3--->49
Thread-2--->48
Thread-0--->47
Thread-3--->46
Thread-1--->45
Thread-2--->44
Thread-0--->43
Thread-1--->42
Thread-3--->41
Thread-0--->40
Thread-2--->39
Thread-2--->38
Thread-3--->37
Thread-1--->36
Thread-0--->35
Thread-2--->34
Thread-0--->33
Thread-1--->32
Thread-3--->31
Thread-1--->30
Thread-2--->29
Thread-0--->28
Thread-3--->27
Thread-2--->26
Thread-0--->25
Thread-1--->24
Thread-3--->23
Thread-2--->22
Thread-0--->21
Thread-3--->19
Thread-1--->20
Thread-1--->18
Thread-3--->17
Thread-2--->16
Thread-0--->15
Thread-3--->14
Thread-0--->11
Thread-2--->12
Thread-1--->13
Thread-3--->10
Thread-1--->9
Thread-0--->8
Thread-2--->7
Thread-1--->6
Thread-3--->5
Thread-2--->4
Thread-0--->3
Thread-3--->2
Thread-1--->1
Thread-2--->0
Thread-0--->-1
Thread-3--->-2
|