黑马程序员技术交流社区
标题:
java多线程操作共享数据问题
[打印本页]
作者:
adamjy
时间:
2014-4-21 18:59
标题:
java多线程操作共享数据问题
本帖最后由 adamjy 于 2014-4-21 20:30 编辑
代码如下
public class ThreadTest extends Thread{
private String name ;
static int num = 0 ;
public ThreadTest(String name)
{
this.name = name ;
}
public String getThreadName()
{
return this.name;
}
public void run ()
{
for ( ;num < 10; num++ )
{
System.out.println(num);
try{
Thread.sleep(200);
}
catch(InterruptedException e){
System.out.println("interrupt");
}
}
System.out.println(this.getThreadName()+" over");
this.interrupt();
}
public static void main(String[] args) {
ThreadTest a = new ThreadTest("Thread a");
ThreadTest b = new ThreadTest("Thread b");
a.start();
// 待num的值增加到4的时候,启动线程b
// 为什么不行?
while (true)
{
if ( num > 4 && !b.isAlive())
b.start();
}
}
}
复制代码
请问,为什么main()方法中的Thread b没有启动起来?
作者:
你为谁归来
时间:
2014-4-21 19:22
因为在你a线程还没执行到num大于4的时候,主线程就已经把下面的代码执行了。
作者:
osully
时间:
2014-4-21 19:29
貌似是主线程无限死循环的原因吧
我只加了个1毫秒延迟 b就出来了
while (true) {
if (num > 4 && !b.isAlive()) {
b.start();
}
try {
Thread.sleep(1);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
复制代码
作者:
曹冬明
时间:
2014-4-21 19:39
public class ThreadTest extends Thread{
private String name ;
static int num = 0 ;
public ThreadTest(String name)
{
this.name = name ;
}
public String getThreadName()
{
return this.name;
}
public void run ()
{
for ( ;num < 10; num++ )
{
System.out.println(Thread.currentThread().getName()+"--"+num);//这里我改了下方便看线程启动
try{
Thread.sleep(200);
}
catch(InterruptedException e){
System.out.println("interrupt");
}
}
System.out.println(this.getThreadName()+" over");
this.interrupt();
}
public static void main(String[] args) {
ThreadTest a = new ThreadTest("Thread a");
ThreadTest b = new ThreadTest("Thread b");
a.start();
// 待num的值增加到4的时候,启动线程b
// 为什么不行?
while (true)
{
if ( num > 4 && !b.isAlive())
b.start();
if (num>=10)
{
break;
}
}
}
}
复制代码
因为下面的while循环的问题,当num>=10的时候,while里面的值是true,当你run方法里interrupt方法调用之后,b线程就中断了,因为是true,还会启动b.start,一个线程被启动两次就会报非法线程声明异常,所以,线程b有启动,只是程序没有正常关闭而已,所以加一个判断条件就好了!!代码帮你改过了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2