A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 佛山java爱好者 中级黑马   /  2014-7-8 13:52  /  553 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 佛山java爱好者 于 2014-7-9 08:15 编辑

为什么不管有没有Thread.sleep(),打印出来的currentThread都只有Thread-0而没有Thread-1?怎样改才能让两个线程同时运行(并保证同步)?
public class ThreadDemo6{ public static void main(String args[])
{  
ThreadTest b=new ThreadTest();  
new Thread(b).start();  
try{Thread.sleep(1);
}
catch (Exception e){}  
b.a=1;  
new Thread(b).start();
}
}
class ThreadTest implements Runnable
{ int t=280;
int a=0;
public void run()
{  synchronized (this)
{   if (this.a==0)
  {    while (t>0)   
{     System.out.println(Thread.currentThread().getName()+" "+t--);  
  }   
}   
else   {    while (t>0)   
{     
System.out.println("看 起 来 长 一 点 "+Thread.currentThread().getName()+" "+t--);    }
  }
  }
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马