【发布时间】:2016-03-22 20:50:11
【问题描述】:
我对将实例和局部变量作为参数传递给线程有疑问。
让我给你看一个简单的例子:
public class Foo {
private int num;
private String str;
public Foo(int num, String str){
this.num = num;
this.str = str;
}
public int getNum() {
return num;
}
public String getStr() {
return str;
}
}
public class FooRunnable implements Runnable {
private Foo foo;
public FooRunnable(Foo foo){
this.foo = foo;
}
@Override
public void run() {
System.out.println("Number =" +foo.num);
System.out.println("String =" +foo.str);
}
}
public class Test {
private Foo fooField;
public Test(){
fooField = new Foo(4, "four");
}
public void launchField(){
Thread th = new Thread(new FooRunnable(fooField));
th.start();
}
public void launchLocalVariable(){
Foo fooLocal = new Foo(5, "five");
Thread th = new Thread(new FooRunnable(fooLocal));
th.start();
}
public static void main(String[] args) {
Test test = new Test();
test.launchField();
test.launchLocalVariable();
}
}
这只是一个启动两个线程的愚蠢程序:一个将实例变量作为参数传递给线程,另一个传递一个局部变量。之后,两个线程将传入参数的内容写入控制台。
对于局部变量,我确信它的行为是线程安全的。在第二种情况下,我认为它不会,因为可能缓存了该变量。你怎么看待这件事?我错了吗?
【问题讨论】:
标签: java multithreading thread-safety