美文网首页
多线程交替打印

多线程交替打印

作者: couriravant | 来源:发表于2020-01-07 00:41 被阅读0次

多线程打印1~100:

public class MutillThread {

    private static Lock lock = new ReentrantLock();
    private static int state = 0;
    private static  int count = 1;

    static class MyThread extends Thread {
        int num;

        public MyThread( int num) {
            this.num = num;
        }

        @Override
        public void run() {
            while(count < 100) {
                try{
                    lock.lock();
                  //这里要double check count <=100,不然最后一个线程已经通过了外层判断在这里等待会继续打印101
                    while(state % 4 == num && count <=100) {
                        System.out.println(Thread.currentThread().getName()+": "+count);
                        state++;
                        count++;
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        new MyThread( 0).start();
        new MyThread( 1).start();
        new MyThread(2).start();
        new MyThread(3).start();
    }
}

但是我没想明白count为什么不加voliatle也可以。

相关文章

网友评论

      本文标题:多线程交替打印

      本文链接:https://www.haomeiwen.com/subject/slwlactx.html