【问题标题】:Changing an arrays elements with thread使用线程更改数组元素
【发布时间】:2019-01-01 21:34:30
【问题描述】:

我需要使用线程来更改数组的元素。它应该随机更改(添加或减去整数)一个元素,休眠 2 秒并随机更改另一个。

所以我创建了我的数组和我的线程,但我不知道如何更改它。

public static void main(String[] args) {

    int [] myarray= new int[5]; 
    Thread x= new Thread();
    x.start(); 

    try 
        {
            x.sleep(2000);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }

}

}
public class myThread implements Runnable {
   public myThread(){ //an empty constructor, to pass parameters

   }
    public void run(){

    }
    public void update(){ //i tohught i could use that for changing elements

    }

【问题讨论】:

  • 不相关: x.sleep(2000) 是错误代码。方法sleepstatic,所以应该通过类名限定调用,而不是实例值,所以应该是Thread.sleep(2000)
  • 您需要将数组作为参数传递给构造函数。此外,您需要实际使用 myThread 类。请注意,Java 命名约定是类名以大写字母开头,因此应称为MyThread

标签: java arrays multithreading


【解决方案1】:

首先,您必须创建一个类声明,它接受所需的arr 并通过逻辑实现run() 方法。

public static class MyThread implements Runnable {

    private final int[] arr;
    private final Random random = new Random();

    private MyThread(int[] arr) {
        this.arr = arr;
    }

    @Override
    public void run() {
        try {
            while (true) {
                // wait for 2 seconds
                Thread.sleep(TimeUnit.SECONDS.toMillis(2));
                // randomly choose array element
                int i = random.nextInt(arr.length);
                // randomly choose increment or decrement an elements
                boolean add = random.nextBoolean();

                // lock WHOLE array for modification
                synchronized (arr) {
                    arr[i] = add ? arr[i] + 1 : arr[i] - 1;
                }
            }
        } catch(InterruptedException e) {
        }
    }
}

其次,你必须创建一个数组和需要修改的线程数。

// create an array
int[] arr = new int[5];

// create threads and start
for (int i = 0; i < 20; i++)
    new Thread(new MyThread(arr)).start();

基本上就是这样。当然,可以不锁定整个数组以仅修改一个元素,但这是另一回事。

【讨论】:

  • 主例程中的最后一个println(...) 调用可以在工作线程仍在运行时执行。不是任何人都可以通过检查程序的输出来判断,但仍然......你确定这就是你想要展示的吗?
  • 我不明白为什么输出是 [0, 0, 0, 0, 0]
猜你喜欢
  • 2016-08-08
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
相关资源
最近更新 更多