2010-08-17 89 views
0

Join方法如何在线程中工作。如果在run方法中写入连接方法,那么它将会死锁。只需要了解为什么发生这种情况。Java线程加入方法

一小段代码片段:

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"); 
    } 

} 

我只是想完成线程1前thread3及线程

+0

首先你有什么想法如何加入方法工作? – JegsVala 2014-06-04 05:36:58

回答

1

你还没有解释什么threadObj3是...是同一线程参考?如果是这样,它将会陷入僵局是可以理解的 - 它会一直等到它完成,但它不会执行,因为它在等待!

你究竟在努力实现什么?

0

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

+0

优先级更多的是建议而不是保证。 – Pops 2010-08-17 21:14:49