读书人

小弟我想验证一下线程不同步时成员变

发布时间: 2013-12-20 17:03:19 作者: rapoo

我想验证一下线程不同步时,成员变量会一致时
public class TestTongbu{
public static int i=0;
public static void main(String [] args){
//这里错了?提示:无法从静态上下文中引用非静态变量 this?
mythread t1=new mythread("t1");
mythread t2=new mythread("t2");
t1.start();
t2.start();
}
class mythread extends Thread {
mythread(String s){
super(s);
}
public void run(){
i++;
try{
Thread.sleep(1);
}catch(InterruptedException e){
return;
}
System.out.println(Thread.currentThread().getName()+i);
}
}
}



----------- //这里错了?提示:无法从静态上下文中引用非静态变量 this?
mythread t1=new mythread("t1");
mythread t2=new mythread("t2");
------ 我该怎么修改才能通过编译程序,看到不同步的效果呀
[解决办法]

引用:
方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。
[解决办法]
你想验证,最好在 i++ 加上个循环,比如100次。这样能明显看出异常。
然后还要在两个start之后加上
t1.join();
t2.join();
等线程执行完。
最后在print i。

[解决办法]
引用:
Quote: 引用:

方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。



可以的,i换成TestTongbu.i啊。
[解决办法]
引用:
Quote: 引用:

Quote: 引用:

方法1、加static
static class mythread extends Thread

方法2、将mythread类定义移动到TestTongbu类外部
public class TestTongbu{
//...
}
class mythread extends Thread{

}

他想要线程间共享变量,你的方法2对于他不合适。



可以的,i换成TestTongbu.i啊。

对。它的i静态的。是可以。



嘻嘻没注意。

楼主结贴给分!!!小弟我想验证一下线程不同步时,成员变量会一致时小弟我想验证一下线程不同步时,成员变量会一致时

读书人网 >J2SE开发

热点推荐