我需要在我的Main类的main()方法中定义一个共享变量。我需要两个线程才能访问该共享变量。我通过实现Runnable接口并实现接口的抽象run()方法来创建线程。在我的类中定义的实现Runnable接口的run()方法内,我如何引用Main类的main()方法中定义的共享变量?显然,只是通过名称调用它们不起作用 - 因为它们看起来超出了我的Runnable类的范围。从Runnable类中访问共享变量
编辑 - 道歉,这里是一个简单的例子
public Class DoThread implements Runnable {
public void run(){
sharedVar += 1
}
}
并在一个单独的.class文件:
public Class Main {
public static void main(String[] args) {
int sharedVar = 0;
Thread t1 = new Thread(new DoThread());
Thread t2 = new Thread(new DoThread());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
所以我应该被创建一个对象到共享VAR存储在再在创建线程时将该对象传递给DoThread()构造函数?我有时在java通过ref传递或var传递之间感到困惑,所以如果我这样做,将通过t2看到由t1改变共享变量吗?
你能发布你的代码吗? – SJuan76
总是尝试发布[SSCCE](http://sscce.org/)。 –