启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20.

启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75.

//没有注释
package com.ry.test;

public class Test01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new runnable1(1));
        Thread t2 = new Thread(new runnable1(2));
        Thread t3 = new Thread(new runnable1(3));
        t1.start();
        t2.start();
        t3.start();
    }
}

class runnable1 implements Runnable {
    private int cid;
    private int sid = 0;
    static private int count = 0;

    public runnable1(int cid) {
        this.cid = cid;
    }

    @Override
    public void run() {
        while (count<75) {
            synchronized (runnable1.class) {
                sid = count / 5 % 3 + 1;
                if (sid == cid) {
                    for (int i = 0; i < 5; i++) {
                        System.out.println("线程" + cid + ":" + (++count));
                    }
                    System.out.println();
                    runnable1.class.notifyAll();
                } else {
                    try {
                        runnable1.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
    }
}

//包含注释

package com.ry.test;

public class Test01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new runnable1(1));
        Thread t2 = new Thread(new runnable1(2));
        Thread t3 = new Thread(new runnable1(3));
        t1.start();
        t2.start();
        t3.start();
    }
}

class runnable1 implements Runnable {
    private int cid;//记录当前线程的标记
    private int sid = 0;//应该轮到哪一个线程
    static private int count = 0;
    //用不到无参构造,也就没写
    //有参构造
    public runnable1(int cid) {
        this.cid = cid;//当前线程标记
    }
    @Override
    public void run() {
        while (count < 75) {//循环条件呀,不能超过75,到了75就完事下课打包回家呗!
            synchronized (runnable1.class) {
                sid = count / 5 % 3 + 1;//计算当前应该轮到哪个线程
                if (sid == cid) {//当前线程就是应该轮到的
                    for (int i = 0; i < 5; i++) {
                        System.out.println("线程" + cid + ":" + (++count));
                    }
                    System.out.println();
                    runnable1.class.notifyAll();//我这一轮完事了,你们谁来?看看下一轮我还能不能上!
                } else {//当前线程不是应该轮到的
                    try {
                        runnable1.class.wait();//当前线程别着急再等等!快轮到你了!
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
    }
}

你可能感兴趣的:(线程,多线程)