多次运行n个线程

时间:2017-05-07 08:11:31

标签: java multithreading

我想运行m次的多个(n)线程计数。例如3个线程7次。并希望输出为6到0.最后我想要这样的输出。

Thread 0 - count 6
Thread 1 - count 5

Thread 0 - count 4
Thread 1 - count 3

Thread 0 - count 2
Thread 1 - count 1

Thread 0 - count 0  // when count is 0 i want to exit.

我写了这个程序,但无法弄清楚如何得到这个输出。

Main.java - >

public class Main {

 static boolean isWaiting(MyThread[] arr) {
    for (MyThread item : arr) {
        if (!item.getState().toString().equals("WAITING")) {
            return false;
        }
    }
    return true;
 }

 public static void main(String[] args) {

    int numberOfThreads = 3; //not a fix number
    int numberOfRepeats = 7; //not a fix number

    MyThread[] threads = new MyThread[numberOfThreads];

    for (int i = 0; i < (numberOfThreads - 1); i++) {
        threads[i] = new MyThread();
    }
    threads[threads.length - 1] = new MyLastThread(numberOfRepeats);

    for (int i = 0; i < (numberOfThreads - 1); i++) {
        threads[i].setNext(threads[i + 1]);
    }
    threads[threads.length - 1].setNext(threads[0]);

    for (int i = 0; i < numberOfThreads; i++) {
        threads[i].start();
    }

    while (true) {
        if (isWaiting(threads)) {
            synchronized (threads[0]) {
                threads[0].notify();
            }
            break;
        }
    }
 }
}

MyThread.java - &gt;

public class MyThread extends Thread {

 protected MyThread next;

 MyThread() {
 }

 public void setNext(MyThread next) {
    this.next = next;
 }

@Override
 public void run() {
    while (true) {
        justDoIt();
    }

 }

 protected void writeMyName() {
    System.out.println(this.currentThread().getName());
 }

 protected void justDoIt() {
    synchronized (this) {
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }

    writeMyName();

    synchronized (next) {
        next.notify();
    }
 }
}

MyLastThread.java - &gt;

public class MyLastThread extends MyThread {
 private int numberOfRepeats;
 private int countOfRepeats;

 public MyLastThread(int numberOfRepeats) {
    this.numberOfRepeats = numberOfRepeats;
 }

 @Override
 public void run() {
    while (true) {
        countOfRepeats++;

            synchronized (this) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                }
            }

            writeMyName();
        if (countOfRepeats < numberOfRepeats) {
                synchronized (this.next) {
                next.notify();
            }
        } else {
            System.exit(0);
        }
    }
 }

 @Override
 protected void writeMyName() {
    super.writeMyName();
    System.out.println();
 }
}

当我运行它时,3个线程重复7次。这不是我想要的。而且我认为我使用的代码比我想要的更多。我需要帮助来获得我想要的输出。我也想写这个程序而不使用“sleep()”或等待数字“wait(num)”。谢谢

0 个答案:

没有答案