繁体   English   中英

使用线程更改数组元素

[英]Changing an arrays elements with thread

我需要使用线程更改数组的元素。 它应该随机更改(添加或减去整数)一个元素,休眠 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

    }

首先,您必须创建一个类声明,它接受所需的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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM