使用监视器类

时间:2015-08-15 13:56:46

标签: java multithreading

以下程序创建生成随机数的线程。

如何更改Monitor,以便它按照每个线程ID的顺序打印打印输出的方式控制线程?< / p>

&#34>等解决方案调用run方法代替start&#34;不接受。

给定的分类是:

public class Main {
    public static void main(String[] args) {
        Monitor mon = new Monitor();
        for (int i = 0; i < 20; i++)
            new T(i, mon).start();

        System.out.println("Finished");
    }
}
public class Monitor {

    public void print(int id, int num) {
        System.out.println("id=" + id + " num=" + num);
    }
}
public class T extends Thread {
    private int id;
    private Monitor mon;

    public T(int i, Monitor m) {
        id = i;
        mon = m;
    }

    private int calc() {
        int num = 0;
        for (int i = 0; i < 10; i++)
            num = num + (int) (Math.random() * 10);
        return num;
    }

    public void run() {
        int num = calc();
        mon.print(id, num);
    }
}

2 个答案:

答案 0 :(得分:3)

您只需要尝试打印的线程等待并阻塞,直到其ID为预期ID:

public class Monitor {

    private final Object lock = new Object();
    private int expectedId = 0;

    public void print(int id, int num) {
        synchronized (lock) {
            while (id != expectedId) {
                try {
                    lock.wait();
                }
                catch (InterruptedException e) {
                    return;
                }
            }
            System.out.println("id=" + id + " num=" + num);
            expectedId++;
            lock.notifyAll();
        }
    }
}

答案 1 :(得分:1)

对于奇怪的任务,只能提出奇怪的解决方案。我的版本是这样的:

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Monitor {
    Map<Integer, Integer> map = new TreeMap<>();

    public synchronized void print(int id, int num) {
        map.put(id, num);
        if(map.size() == 20) {
            for(Entry<Integer, Integer> entry : map.entrySet())
            System.out.println("id=" + entry.getKey() + " num=" + entry.getValue());
        }
    }
}

它解决了你的问题。不接受诸如“它取决于线程数”之类的反对意见。