• java并发编程实战第一章


    线程不安全代码测试
        private static class UnsafeSequence {
            private int value;
    
            public int getNext() {
                return value++;
            }
        }
    

    使用两个线程分别调用上面的getNext方法1000次,出现了一次线程不安全的情况,在转出的结果中有两个1311:


     
    图片.png

    原因分析,与书上说的一致:


     
    图片.png

    完整的代码
    import java.io.PrintWriter;
    import java.util.concurrent.CountDownLatch;
    
    /**
     * Created by luohao07 on 2018/1/2.
     */
    public class UnsafeSequenceTest {
    
        public static void main(String[] args) throws Exception{
            UnsafeSequence unsafeSequence = new UnsafeSequence();
            PrintWriter out = new PrintWriter("out.txt");
            CountDownLatch countDownLatch = new CountDownLatch(2);
            new Thread() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        out.println(unsafeSequence.getNext() + " T1");
                    }
                    countDownLatch.countDown();
                }
            }.start();
    
            new Thread() {
                @Override
                public void run() {
                    for (int i = 0; i < 1000; i++) {
                        out.println(unsafeSequence.getNext()+" T2");
                    }
                    countDownLatch.countDown();
                }
            }.start();
    
            countDownLatch.await();
            out.flush();
            out.close();
        }
    
        private static class UnsafeSequence {
            private int value;
    
            public int getNext() {
                return value++;
            }
        }
    }
    
    
    Timer执行定时任务
    public class TimerTest {
        public static void main(String[] args) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("invoke....");
                }
            }, new Date(System.currentTimeMillis() + 5000));
        }
    }
    

    程序启动后5秒输出invoke....

    欢迎加入学习交流群569772982,大家一起学习交流。
  • 相关阅读:
    eclipse快捷键
    NetBeans无法使用svn相关功能
    sqlplus执行startup出现ORA-00119,ORA-00132错误
    Oracle中对number类型数据to_char()出现各位少0,或者值为###的处理
    服务器启动报mybatis配置错误
    Java Thread interrupt
    nginx backend 健康检查
    SSH 安全建议
    ARP
    Postgresql 锁查看
  • 原文地址:https://www.cnblogs.com/z335/p/8178831.html
Copyright © 2020-2023  润新知