在复习毕向东老师的java视频--(138多线程-同步函数的锁是this)时(代码如下),对线程运行产生了一些疑惑,主要在后四句:
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag = false;
- t2.start();
复制代码 flag是为了让同步代码块和同步函数交替执行。
虽然老师让主线程等待了一会时间,但是flag还是被赋值flase,此时同步代码块应该不被执行,为什么结果还是同步代码块与同步函数交替执行?
希望同志们多多帮助
- class Ticket implements Runnable
- {
- private int tick = 100;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....code : "+ tick--);
- }
- }
- }
- }
- else
- while(true)
- show();
- }
- public synchronized void show()//this
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);
- }
- }
- }
- class ThisLockDemo
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag = false;
- t2.start();
- // Thread t3 = new Thread(t);
- // Thread t4 = new Thread(t);
- // t3.start();
- // t4.start();
- }
- }
复制代码
|
|