按顺序运行线程

时间:2015-07-12 09:44:40

标签: java multithreading

假设我下面有以下类,如何依次强制执行三个线程,一个接一个地执行? (等待彼此终止)

public void feed(List<Cat> animals) {
    this.feed(animals, this.catFood);
}

2 个答案:

答案 0 :(得分:2)

是的,但你为什么要这样做?

public static void main(String[] args) throws InterruptedException{

    Thread thread1 = new Thread(new MyRunnable());      
    Thread thread2 = new Thread(delay()); 
    Thread thread3 = new Thread(waiting()); // (initial state)

    thread1.start();
    thread1.join();
    thread2.start();
    thread2.join();
    thread3.start();
    thread3.join();
}

其他方式(没有线程):

public static void main(String[] args) throws InterruptedException{

    new MyRunnable().run();
    delay().run(); 
    waiting().run();
} 

您的代码执行此操作:

Main thread      thread-1        thread-2       thread-3
    V
    |
    + . . . . . . > V
    + . . . . . . . | . . . . . . > V
    + . . . . . . . | . . . . . . . | . . . . . . > V
    X               |               |               |
                    X               |               |
                                    |               |
                                    X               |
                                                    |
                                                    X    

你问过这个问题(没有任何意义,因为线程可以并行化任务,而你不想并行化它们!):

Main thread      thread-1        thread-2       thread-3
    V
    |
    + . . . . . . > V
    |               |
    |<--------------X
    + . . . . . . . . . . . . . . > V
    |                               |
    |                               |
    |                               |
    |                               |
    |<------------------------------X
    + . . . . . . . . . . . . . . . . . . . . . . > V
    |                                               |
    |                                               |
    |                                               |
    |                                               |
    |                                               |
    |                                               |
    |<----------------------------------------------X
    X

答案 1 :(得分:0)

启动线程后放置thread.join ()。这将等待线程在下一个线程开始之前返回。

相关问题