2011-06-21 81 views
0

我有一个类ThreadClass看起来如下:Java线程问题

public class ThreadClass extends Thread{ 

    String msg; 

    public void run() 
    { 
     for(int i=0;i<=5;i++) 
     { 
      System.out.println("Run method: "+msg); 
     } 
    } 

    ThreadClass(String mg) 
    { 
     msg=mg; 
    } 

}

public class MainThreadClass { 

    public static void main(String[] args) { 

     ThreadClass dt1=new ThreadClass("Thread 1"); 
     ThreadClass dt2=new ThreadClass("Thread 2"); 

     dt1.start(); 
     dt2.start(); 

     System.out.println("Finished"); 
    } 
} 

我得到的输出是:

Run method: Thread 1 
Finished 
Run method: Thread 1 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 1 
Run method: Thread 1 
Run method: Thread 1 
Run method: Thread 1 

我想输出实现将是:

Run method: Thread 1 
Run method: Thread 1 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 2 
Run method: Thread 1 
Run method: Thread 1 
Run method: Thread 1 
Run method: Thread 1 
Finished 

因此当这两个线程终止时,打印完字符串。怎么做?

回答

1

等待每个线程退出使用join()

public class MainThreadClass { 
    public static void main(String[] args) { 

    ThreadClass dt1=new ThreadClass("Thread 1"); 
    ThreadClass dt2=new ThreadClass("Thread 2"); 

    dt1.start(); 
    dt2.start(); 

    dt1.join(); 
    dt2.join(); 

    System.out.println("Finished"); 
    } 
} 

[对不起糟糕的格式,由于某种原因,我不能让这种期待任何更好。 IE问题也许]

+0

@Radek - 看不到你这里张贴的输出,但你不能指望你的孩子线程的输出确定性交织,除非你强制执行此使用锁定。 –

0

您需要确定当一个线程结束:

// Create and start a thread 
Thread thread = new MyThread(); 
thread.start(); 

// Check if the thread has finished in a non-blocking way 
if (thread.isAlive()) { 
    // Thread has not finished 
} else { 
    // Finished 
} 

// Wait for the thread to finish but don't wait longer than a 
// specified time 
long delayMillis = 5000; // 5 seconds 
try { 
    thread.join(delayMillis); 

    if (thread.isAlive()) { 
    // Timeout occurred; thread has not finished 
    } else { 
    // Finished 
    } 
} catch (InterruptedException e) { 
    // Thread was interrupted 
} 

// Wait indefinitely for the thread to finish 
try { 
thread.join(); 
    // Finished 
} catch (InterruptedException e) { 
    // Thread was interrupted 
} 
0

或者使用一个ExecutorService。以下是我和你们类似的课程摘录。

ExecutorService l_service = Executors.newFixedThreadPool(l_number_threads); 
List<Future<T>> l_results = null; 
try { 
    l_results = l_service.invokeAll(a_tasks); 
} catch (InterruptedException ex) { 
    throw ex; 
} 
l_service.shutdownNow();