goback add

java例程练习(多线程[join()方法])

3363 点击·0 回帖
灯火互联
楼主

public class Test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread("m1");
        myThread.start();   //产生分支,子线程开始执行
        
        try{
            myThread.join();//------等待合并myThread子线程,主线程才开始执行
        } catch(interruptedException e) {}
        
        for(int i = 1; i <= 10; i++) {
            System.out.println("I am main thread");
        }
    }
}

class MyThread extends Thread {
    MyThread(String s) {//给线程起名字的构造方法
        super(s);
    }
    public void run() {
        for(int i = 0 ; i <= 10; i++) {
            System.out.println("I'm " + getName());
            try {
                sleep(1000);
            } catch(InterruptedException e) {
                return;
            }
        }
        
    }
}

喜欢0 评分0