【问题标题】:Java threads starting other threads, each writing into arrayJava线程启动其他线程,每个线程写入数组
【发布时间】:2014-10-23 21:16:28
【问题描述】:

对 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);
            } 

    }

}

【问题讨论】:

  • 我的主要意见是,如果您对 Java 完全不熟悉,那么这不是解决问题的正确问题!
  • 我完全同意,但我得到了几行代码,展示了如何创建一个线程,让它打印一个单词,并且它被一些人认为足够了 -.- 如果我能弄清楚如何为了让线程的 run() 写入数组并唤醒其他线程,我想我可以弄清楚其余的。
  • notifyAll() 方法通知所有等待的线程。我猜你需要学习 wait(),notifyAll()
  • 你是怎么得到这个的?是作业吗?您应该向您的助教或教授寻求帮助,他们需要知道学生何时遇到作业问题。
  • 从每个线程将值写入 resultArray 怎么样?

标签: java arrays multithreading thread-sleep notify


【解决方案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 

【讨论】:

  • 谢谢。正是我需要的。如果您不介意,我有几个问题: 1. @Override 真的需要吗? (这实际上不会在任何地方“使用”,只是一个任务) 2. 这个程序中的“final”有什么不同? 3. 有没有什么办法可以让打印结果总是显示在最后?如果我运行它几次,它会很快打印出结果,以至于线程开始消息在最后:D
  • @GytisK 1. 这不是真正需要的,只是一种好的编码风格,有助于编译器帮助您防止错误。 2. 同样,这是一个很好的做法,可以帮助您最大限度地减少产生错误的机会。 3. 是的,您必须使用记录器(它将保留调试消息的顺序并打印它们 fifo)
  • 如果没有threadList,我将如何用最后一个线程通知所有线程?我使用了(在 main 中) else { synchronized(this){this.notifyAll()} },完成后它并没有停止程序。
猜你喜欢
  • 2016-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多