格式:以加入A線程為例
線程對象B.join() 無參數,則A線程一直暫停,直到B線程運行結束。
線程對象B.join(時間t) 有參數,則A線程每隔t時間暫停一次,直到B線程運行結束。
關於while(true)無限循環,參考https://blog.csdn.net/m1598306557/article/details/78176576
案例:線程A達到20%時,線程B加入

public class Demo extends JFrame { private Thread threadA;//定義線程 private Thread threadB; final JProgressBar progressBar1 = new JProgressBar();//進度條 final JProgressBar progressBar2 = new JProgressBar(); public Demo() { setBounds(100, 100, 200, 100); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); getContentPane().add(progressBar1, BorderLayout.NORTH); getContentPane().add(progressBar2, BorderLayout.SOUTH); progressBar1.setStringPainted(true);//顯示數字 progressBar2.setStringPainted(true); //使用匿名內部類實現Runnable接口 threadA = new Thread(new Runnable() { int count = 0;//進度數據 public void run() { while (true) {//無限循環,一般在不知道循環次數時使用 progressBar1.setValue(++count); try { Thread.sleep(100);//休眠0.1s if (count==20){ threadB.join();//線程B加入, } } catch (InterruptedException e) { e.printStackTrace(); } if (count == 100) break; } } }); threadA.start(); threadB = new Thread(new Runnable() { int count = 0;//進度數據 public void run() { while (true) { progressBar2.setValue(++count); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if (count == 100) break; } } }); threadB.start(); setVisible(true); } public static void main(String[] args) { new Demo(); } }
