线程不共享相同的数据变量

时间:2017-04-07 16:19:08

标签: java multithreading

我是Java的新手。我的老师给了我关于多线程的作业,其中有两个线程Example和Example1。 示例对线程进行更改,Example1读取它。 但是,当我实现Example1线程时,无法正常工作。

示例线程:

public class Example extends Thread {
    public int[] array = {2,1,0,5,9};
    public void run(){
        for(int i=0; i<array.length;i++){
            array[i] = array[i]+i;
            System.out.println(getName()+" : "+array[i]);
        }
    }
}

示例1线程:

public class Example1 extends Example implements Runnable {

    @Override
    public void run(){
        for(int i=0;i<array.length;i++){
            System.out.println(getName()+" : "+array[i]);
        }
    }
}

主要:

public class TestExample {

    public static void main(String[] args) {
        Example t1 = new Example();
        t1.setName("t1");
        t1.start();

        Example1 obj = new Example1();
        Thread t2 = new Thread(obj);
        t2.setName("t2");
        t2.start();
    }

}

,输出为:

t1 : 2
t1 : 2
t1 : 2
t1 : 8
t1 : 13
Thread-1 : 2
Thread-1 : 1
Thread-1 : 0
Thread-1 : 5
Thread-1 : 9

即使Example已经对int []数组进行了更改,线程Example1也无法读取int []数组中的更改值。 可能是什么问题以及如何纠正它?

3 个答案:

答案 0 :(得分:0)

将int []数组设为静态。

public static int[] array = {2,1,0,5,9};

输出:

t1 : 2
t1 : 2
t1 : 2
t1 : 8
t1 : 13
t2 : 2
t2 : 2
t2 : 2
t2 : 8
t2 : 13

答案 1 :(得分:0)

我认为你的问题是误解了实例化的概念。

你有一个数组存在于对象本身,因此每次实例化时,都会在该新对象内部创建一个不同的数组。

这与标记某些东西&#34;静态&#34;不同。这将迫使它有一个实例。

所以你有两个选项,使用一个单独的静态项来引用它将在所有实例之间共享

OR

传递数组或包含线程对象之间数组的某些数据结构,这样你实际上就是在操作它而不是在创建线程对象时创建两个不同的数组

答案 2 :(得分:0)

您可以使用静态,但更好的OO方式:将其设为实例字段,例如:

public class Example extends Thread {
  private int[] array;
  public Example(int[] array) {
    this.array = array;
  }
...

类似于Example2;然后你进入你的主要:

 int[] array = { 1, 2, 3, 4 };
 Example ex1 = new Example(array);

换句话说:您的两个类正在处理两个不同的数组对象。只需将相同的对象交给您的两个线程!

只是为了确定:当您添加此代码时;您可能仍会看到令人惊讶的结果 - 因为您有两个线程处理相同的数组;可能并行。所以要为各种意想不到的输出做好准备!