volatile+AtomicInteger

 

 

 

public class Demo3Volatile {

    public static void main(String[] args) throws InterruptedException {
        VolatileDemo demo = new VolatileDemo();

        List<Thread> list = new ArrayList<Thread>();
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(demo);
            list.add(t);
            t.start();
        }


        Thread.sleep(1000);
//
//        for (Thread thread : list) {
//            thread.interrupt();
//        }

        System.out.println(demo.count);
    }

    static class VolatileDemo implements Runnable {
        public volatile int count;
        //public volatile AtomicInteger count = new AtomicInteger(0);

        public void run() {
            addCount();
        }

        //可重入锁
        private Lock lock = new ReentrantLock();

        public void addCount() {
            for (int i = 0; i < 10000; i++) {
                //synchronized (this) {
                    lock.lock();
                    count++;
                    lock.unlock();
                //}

                //使用原子操作类
                //count.incrementAndGet();

//                if (Thread.currentThread().interrupted()) {
//                    break;
//                }
            }
        }
    }
}

 

posted @ 2021-11-20 20:20  AngDH  阅读(26)  评论(0编辑  收藏  举报