Java Thread Join方法

时间:2010-08-17 17:30:12

标签: java

Join方法如何在Thread中工作。如果在run方法中写入join方法那么它将进入deadloack。只需要了解其发生的原因。

Code Snipet:

public class ThreadSchuduling extends Thread{
    static ThreadSchuduling threadObj3;
    public ThreadSchuduling(){
        System.out.println("Default Constructor");
    }
    public ThreadSchuduling(String name){
        System.out.println("Parameter Constructor");
    }
    public void run(){
        try{
            threadObj3.join();
        }catch(Exception e){
            System.out.println("Error in RUN "+e);
        }
        System.out.println(Thread.currentThread().getName());
        for(int i = 0; i < 10; i++){
            System.out.println("Value is = "+i);
        }

    }
    public static void main(String[] args) {
        ThreadSchuduling threadObj1 = new ThreadSchuduling("Thread1");
        ThreadSchuduling threadObj2 = new ThreadSchuduling("Thread2");
        threadObj3 = new ThreadSchuduling("Thread3");
        ThreadSchuduling threadObj4 = new ThreadSchuduling("Thread4");

            threadObj1.start();
            threadObj2.start();
            threadObj3.start();
            System.out.println("Thread 3 is started");
            threadObj4.start();
            try{
            threadObj3.join();

        }catch(Exception e){
            System.out.println("Errpr "+e);
        }
        System.out.println("Main Method completed");
    }

}

我只想在thread1和thread2

之前完成thread3

2 个答案:

答案 0 :(得分:1)

您还没有解释threadObj3是什么...是对同一个帖子的引用?如果是这样,可以理解它会死锁 - 它等到它完成了,它不会因为它在等待而无法做到!

你到底想要实现什么目标?

答案 1 :(得分:0)

OMG,threadObj3总是在等待,如果你想在thread1和thread2之前完成thread3,你可以设置优先级,或者很难确保thread3在其他线程之前执行。