Java线程启动其他线程,每个线程写入数组

时间:2014-10-23 21:16:28

标签: java arrays multithreading thread-sleep notify

完全是Java新手,不过我必须以某种方式完成这项工作。我希望你们能让我走上正确的道路。

程序必须创建N个线程和N个元素的数组。第一个线程应该在数组中写一个随机数(这里是resultArray),调用(或创建)下一个线程(将执行相同的)并休眠直到最后一个线程通知所有其他睡眠线程。

那么,到目前为止我这样做了吗?如何创建run()访问演示的resultArray并在线程的随机数中写入? 另外,run()如何到达其他线程(threadList)来通知他们?

谢谢。

public class gijos extends Thread {

    private int length; 
    private int position;

    public gijos(int arrPos) { 
      position = arrPos;
    } 

    public int getPosition(){
       return position;
    }

    public void run() {   
             Random rand = new Random();
             int  n = rand.nextInt(51) + 1;
    }

public class demo { 

    public static void main (String[] args) { 

            System.out.println("Array length / thread count:");

            Scanner s = new Scanner(System.in);
            int N = s.nextInt();

            int[] resultArray = new int[N];

            gijos[] threadList = new gijos[N]; 

            for(int i = 0; i < N; i++){
                threadList[i] = new gijos(i);
            } 

    }

}

1 个答案:

答案 0 :(得分:1)

这里有一个示例工人类:

public class ArrayWorker implements Runnable {
    private static final List<ArrayWorker> threadList = new LinkedList<>();
    private static final Random rnd = new Random(System.currentTimeMillis());

    private final int[] array;
    private final int index;


    public ArrayWorker(final int[] array, final int index) {
        if (index > array.length - 1) {
            throw new IndexOutOfBoundsException(String.format("%d", index - array.length));
        }

        this.array = array;
        this.index = index;
        System.out.println(this + " has been created");
    }


    @Override
    public void run() {
        System.out.println(this + " run()");
        this.array[this.index] = rnd.nextInt(100);

        if (index < array.length - 2) {
            final ArrayWorker worker = new ArrayWorker(array, index + 1);

            System.out.println(this + " has created: " + worker);
            new Thread(worker).start();

            threadList.add(this);
            try {
                synchronized (this) {
                    System.out.println(this + " is now waiting");
                    this.wait();
                    System.out.println(this + " got notified");
                }
            } catch (InterruptedException ex) {
                System.out.println("Error while waiting for termination");
                threadList.remove(this);
            }
        } else {
            threadList.forEach(worker -> {
                synchronized(worker) {
                    System.out.println(this + " notifying: " + worker);
                    worker.notify();
                }
            });
        }
    }

    @Override
    public String toString() {
        return "WorkerThread[" + index + "]";
    }  
}

这里的用法:

public static void main(String[] args) {
    final int[] myArray = new int[10];

    System.out.println("MainThread creating first WorkerThread and awaiting termination of last WorkerThread");
    Thread t = new Thread(new ArrayWorker(myArray, 0));
    try {
        t.start();
        t.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
        System.exit(-1);
    }

    System.out.println("Last WorkerThread finished");
    for (int i : myArray) {
        System.out.print(i + " ");
    }
    System.out.println();
}

示例输出

MainThread creating first WorkerThread and awaiting termination of last WorkerThread
WorkerThread[0] has been created
WorkerThread[0] run()
WorkerThread[1] has been created
WorkerThread[0] has created: WorkerThread[1]
WorkerThread[1] run()
WorkerThread[0] is now waiting
WorkerThread[2] has been created
WorkerThread[1] has created: WorkerThread[2]
WorkerThread[1] is now waiting
WorkerThread[2] run()
WorkerThread[3] has been created
WorkerThread[2] has created: WorkerThread[3]
WorkerThread[2] is now waiting
WorkerThread[3] run()
WorkerThread[3] notifying: WorkerThread[2]
WorkerThread[3] notifying: WorkerThread[1]
WorkerThread[2] got notified
WorkerThread[3] notifying: WorkerThread[0]
WorkerThread[1] got notified
WorkerThread[0] got notified
Last WorkerThread finished
Results:
10 25 73 7