多个线程顺序打印问题

/**

* 这里默认模拟三个线程顺序打印,所以用正在打印的当前数字printCount%3得到当前期望唤醒的线程

* 另外用ReentrantLock效率应该会更高

*/

public class MyThread extends Thread {

private Object lock;

    //指定线程号

    private int threadCount;

    volatile private static int printCount =1;

    public MyThread(Object lock, int t_count) {

super();

        this.lock = lock;

        this.threadCount = t_count;

    }

@Override

    public void run() {

try {

synchronized (lock) {

while (true) {

if (printCount %3 ==threadCount) {

System.out.println("thread name=" +Thread.currentThread().getName() +"; run count=" +printCount);

                        lock.notifyAll();

                        printCount++;

                        if (printCount  ==99) {

break;

                        }

}else {

lock.wait();

                    }

}

}

}catch (InterruptedException e) {

e.printStackTrace();

        }

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容