在学习毕向东老师的视频中,有如下买票的例子:
- class Ticket implements Runnable{
- private int tick = 500;
- Object o = new Object();
- boolean flag = true;
- public void run(){
-
- while(true){
- synchronized(o){
- if(tick>0)
- System.out.println(Thread.currentThread().getName()+"one---"+tick--);
- }
- }
-
-
-
- }
- }
- public class TicketDemo2{
- public static void main(String[] args){
- 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();
- }
- }
复制代码
上面例子中的票数tick的值为什么最大只能是299,如果设置的值大于299,运行的时候也会从299开始递减。上例程序运行结果如下图:
J:\hh.png |
|