子线程先运行30次主线程,主线程40次,如此循环50次

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35717984/article/details/82494533

以下代码是个人思路,如有不妥请留下宝贵的建议。亲测可以执行

public class MyThread {

    // 子线程先运行30次主线程,主线程40次,如此循环50次?
    public static void main(String[] args) {

        for (int i = 1; i <= 50; i++) {
            System.err.println("第:"+ i +"轮开始");
            Thread main = new Thread(new SonThread(),"a");
            main.start();
            try {
                main.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

// 子线程运行30次
class SonThread implements Runnable{
    @Override
    synchronized public void run() {
        for (int i = 1;i<= 30;i++){
            System.out.println("第:"+ i +"次主线程开始");
            Thread mainThread = new Thread(new MainThread(),"subMain");
            mainThread.start();
            try {
                mainThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 主线程运行40次
class MainThread implements Runnable{
    @Override
    synchronized public void run() {
        for (int i = 1;i<= 40;i++){
            System.out.println("主线程运行第:"+ i +"次");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_35717984/article/details/82494533