本帖最后由 刘佳 于 2012-8-14 10:46 编辑
- class Ticket implements Runnable
- {
- private int tick = 100;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if (flag)
- {
- while (true)
- {
- synchronized(obj)
- {
- 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()
- {
- 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();
- t.flag = false;
- t2.start();
- }
- <font color="red">}</font>
复制代码 上面的是完整的程序代码,该代码中主线程先运行完后,t1,t2两个线程才开始运行。
主线程和多线程不是交替的执行吗,那为何上面代码诠释的含义不同呢?
class ThisLockDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
/*
t1.start()此时为临时状态,一定要等到主线程结束以后才能获得运行资格?
主线程和多线程不能同时交替执行吗?
*/
t.flag = false;
t2.start();
}
}
|