ClassThread
如何从创建此variable var
实例的Class1
实例访问ClassThread
?
ClassThread
public class ClassThread implements Runnable {
@Override
public void run() {
}
}
的Class1
public class Class1 implements Runnable{
public volatile String var;
public Class1() {
}
@Override
public void run() {
for(int i = 0; i < 5; i++){
ClassThread ct = new ClassThread();
Thread t = new Thread(ct);
t.start();
}
}
}
主要
public class Main{
public static void main(String[] args) {
for(int i = 0; i < 3; i++){
Class1 cla = new Class1();
Thread t = new Thread(cla);
t.start();
}
}
}
答案 0 :(得分:1)
将它作为构造函数中的参数:
public class ClassThread implements Runnable {
private volatile String var;
public ClassThread(String var) {
this.var = var;
}
@Override
public void run() {
}
}
在Class1
中,在构建ClassThread
时传递它:
@Override
public void run() {
for(int i = 0; i < 5; i++){
ClassThread ct = new ClassThread(var);
Thread t = new Thread(ct);
t.start();
}
}