簡體   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