谁能证实下面的说法?
Method Arguments and Local Variable declared inside a method is Thread safe; both are exclusive for each invocation of the Thread.
On the other hand Global Variable is shared.
例如
class MyThread implements Runnable{
int _tmp = 10; //SHARED BETWEEN t1, t2, t3, and so on
public void run(){
testThreadConcurrency(arg); // arg is EXCLUSIVE FOR ALL invocation of testThreadConcurrency
}
public void testThreadConcurrency (int num){
int tmp = 10; //EXCLUSIVE FOR ALL invocation of testThreadConcurrency()
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread _runn = new MyThread();
Thread t1 = new Thread(_runn,"t1");
Thread t2 = new Thread(_runn,"t2");
Thread t3 = new Thread(_runn,"t3");
t1.start();
t2.start();
t3.start()
}
**
Please check the output of below program which prove that Global variables are SHARED
**
public class ThreadDemo {
static Object _lock = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread _runn = new MyThread();
Thread t1 = new Thread(_runn,"t1");
Thread t2 = new Thread(_runn,"t2");
Thread t3 = new Thread(_runn,"t3");
t1.start();
try {Thread.sleep(300);} catch (InterruptedException e1) {}
t2.start();
try {Thread.sleep(300);} catch (InterruptedException e1) {}
t3.start();
try {Thread.sleep(300);} catch (InterruptedException e1) {}
synchronized(ThreadDemo._lock){ThreadDemo._lock.notify();}
try {Thread.sleep(300);} catch (InterruptedException e1) {}
synchronized(ThreadDemo._lock){ThreadDemo._lock.notify();}
try {Thread.sleep(300);} catch (InterruptedException e1) {}
synchronized(ThreadDemo._lock){ThreadDemo._lock.notify();}
}
}
class MyThread implements Runnable{
int _tmp = 10;
public void run(){
testTestConcurrency();
}
public void testTestConcurrency(){
if(Thread.currentThread().getName().equals("t2"))
{
_tmp = 20;
}
synchronized(ThreadDemo._lock){try {ThreadDemo._lock.wait();} catch (InterruptedException e) {}}
System.out.println("_tmp = "+_tmp+"|"+Thread.currentThread().getName());
}
}
最佳答案
小心!参数和变量不是对象。假设有几个线程各自进入一个操作List的方法:
public Foo mumbler(List<Bar> barList) {
...
}
方法的每次调用都有自己唯一的 barList 变量。它不能被任何其他线程访问,但如果所有这些变量都持有对同一个 List 对象的引用,那么线程仍然可以(并且可能会)破坏 List 如果它们不通过互斥或某些方式阻止它其他方式。
编辑:
I forgot Java pass primitives as a CallByValue but use CallByReference in case of References....
更好的说法是,Java 按值传递对象引用:
在 C++ 中,您可以这样写:(不是您想要写它:-)
pushValueOnStack(my_type_t value, struct node &top) {
struct node new_node = malloc(sizeof(*new_node));
new_node->value = value;
new_node->next = top;
top = new_node;
}
如果你有一个局部变量,myStack,你调用了pushValueOnStack(someValue, <em>myStack</em>),
它实际上会更改您的局部变量以指向堆栈的新顶部节点。这就是引用调用。这在 Java 中永远不会发生。
关于java - 方法参数和局部变量是线程安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22956866/