引用对象volatile变量的正确实例

时间:2016-02-11 21:27:23

标签: java multithreading

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();
        }
    }
}

1 个答案:

答案 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();
    }
}