Java线程交错运行

时间:2018-10-31 02:01:25

标签: java multithreading

我希望编写一个如下运行流的程序

+Thread 1,2 run together method run of the Runnable
    +If thread 1 runs successfully 
        + thread 2 pause        
        + thread 1 run successfully methodReadResults
            +thread2,thread3 run together
                + thread2 keep running
                + thread 3 run method run of the Runnable

=>直到结束都相同,它类似于在空闲时运行的线程池类型,在线程成功时暂停。 我正在尝试执行的基本代码。

public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
        Person person = new Person("Name " + i);
        Thread thread = new Thread(person);
        thread.start();

        person.methodReadResults();
    }
}

private static class Person implements Runnable {

    private String name;
    private List<Integer> results = new ArrayList<>();

    public Person(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Integer> getResults() {
        return results;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            results.add(i);
        }
    }

    private void methodReadResults() {
        //Read results
        System.out.println(results.size());
    }

如果执行器或预建线程可以用更简单的方式执行我的类型程序,请告诉我。谢谢

0 个答案:

没有答案
相关问题