java里面在主线程产生多个子线程,怎么让这些子线程同时运行,运行完以后再继续执行主线程??

java里面在主线程产生多个子线程,怎么让这些子线程同时运行,运行完以后再继续执行主线程??

package thread;
public class TestJoin {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreJo t= new ThreJo("a");
t.start();
ThreJo t2= new ThreJo("b");
t2.start();
try {
t.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("出错了");
return ;
}
for(int i =0;i<50;i++){
System.out.println("调用主线程第"+i+"次");
}
}

}

class ThreJo extends Thread{

ThreJo(String s){
super(s);
}

public void run(){
for(int i =0;i<50;i++){
System.out.println("继承Thread"+i+"次,我是"+getName());
}
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2014-03-17
public static void main(String[] args) {
int cnt = 10;
ArrayList workers = new ArrayList();
for(int i = 0; i < cnt; i++) {
Thread worker = new Thread(new MyJob());
worker.start();
workers.add(worker);
}

for(int i = 0; i < cnt; i++) {
worker.join(); // 这里表示等待它完成。
}

// 这里面的代码只会在所有 worker 完成之后才运行。
}本回答被网友采纳
第2个回答  2017-09-04
//采用 线程中的jion()方法合并线程 详细案列详见下面的代码

public class MyJionThreadDemo {

public static void main(String[] args) {
JionDemo[] arr=new JionDemo[100];
for(int i=0;i<arr.length;i++){
arr[i]=new JionDemo();
}
for(int i=0;i<arr.length;i++){
try {
arr[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
arr[i].start();
}
for(int i=0;i<100;i++){ //主线程最后运行
System.out.println("线程:"+Thread.currentThread().getName()+"正在运行");
}

}

}

class JionDemo extends Thread{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("线程:"+currentThread().getName()+"正在运行");
}
System.out.println("线程:"+currentThread().getName()+"运行结束");
}
}
第3个回答  推荐于2018-02-27
public class ThreadTest {
    static int i=0;
    public static void main(String[]args){
        //建立3个子线程,以i,i,n,m作为子线程是否结束的判断
        //当所有子线程运行完才开始主线程
        System.out.println("主线程开始");
        Thread t1=new Thread(){
        public void run(){
        System.out.println("子线程1");
        ThreadTest.i+=1;
        }
        };
        //开启线程1
        t1.start();
        Thread t2=new Thread(){
        public void run(){
        try {
        Thread.sleep(1000);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
        System.out.println("子线程2");
        ThreadTest.i+=1;
        }
        };
        //开启线程2
        t2.start();
        Thread t3=new Thread(){
        public void run(){
        System.out.println("子线程3");
        ThreadTest.i+=1;
        }
        };
        //开启线程3
        t3.start();
        boolean res=true;
        while(res){
        //这里判断子线程是否运行完了
        if(ThreadTest.i==3){
        System.out.println("主线程结束");
        res=false;
        }
        }
    }
}

你是想要这效果么

本回答被提问者采纳
第4个回答  2014-03-17
创建完线程让她们全部进入等待状态,然后当最后一个线程创建完毕集体唤醒
相似回答