1.2.4注意Sysyem.out.println与i--

 1 package com.cky.thread;
 2 
 3 /**
 4  * Created by chenkaiyang on 2017/11/27.
 5  */
 6 public class MyThreadThird  extends Thread{
 7     private int count = 5;
 8     @Override
 9     public void run() {
10         super.run();
11         System.out.println("由" + this.currentThread().getName()+"计算count="+count--);
12     }
13 }
 1 package com.cky.test;
 2 
 3 import com.cky.thread.MyThreadThird;
 4 
 5 /**
 6  * Created by chenkaiyang on 2017/11/27.
 7  */
 8 public class Test3 {
 9     public static void main(String[] args) {
10         MyThreadThird mythread = new MyThreadThird();
11         Thread a = new Thread(mythread, "A");
12         Thread b = new Thread(mythread, "B");
13         Thread c = new Thread(mythread, "C");
14         Thread d = new Thread(mythread, "D");
15         Thread e = new Thread(mythread, "E");
16 
17         a.start();
18         b.start();
19         c.start();
20         d.start();
21         e.start();
22 
23 
24     }
25 }
View Code

结果如下

D:itjdk1.8injava -Didea.launcher.port=7540 "-Didea.launcher.bin.path=D:itideaIntelliJ IDEA 2016.3.3in" -Dfile.encoding=UTF-8 -classpath "D:itjdk1.8jrelibcharsets.jar;D:itjdk1.8jrelibdeploy.jar;D:itjdk1.8jrelibextaccess-bridge-64.jar;D:itjdk1.8jrelibextcldrdata.jar;D:itjdk1.8jrelibextdnsns.jar;D:itjdk1.8jrelibextjaccess.jar;D:itjdk1.8jrelibextjfxrt.jar;D:itjdk1.8jrelibextlocaledata.jar;D:itjdk1.8jrelibext
ashorn.jar;D:itjdk1.8jrelibextsunec.jar;D:itjdk1.8jrelibextsunjce_provider.jar;D:itjdk1.8jrelibextsunmscapi.jar;D:itjdk1.8jrelibextsunpkcs11.jar;D:itjdk1.8jrelibextzipfs.jar;D:itjdk1.8jrelibjavaws.jar;D:itjdk1.8jrelibjce.jar;D:itjdk1.8jrelibjfr.jar;D:itjdk1.8jrelibjfxswt.jar;D:itjdk1.8jrelibjsse.jar;D:itjdk1.8jrelibmanagement-agent.jar;D:itjdk1.8jrelibplugin.jar;D:itjdk1.8jrelib
esources.jar;D:itjdk1.8jrelib
t.jar;F:springboot	hreaddemooutproduction	hreaddemo;D:itideaIntelliJ IDEA 2016.3.3libidea_rt.jar" com.intellij.rt.execution.application.AppMain com.cky.test.Test3
由B计算count=3
由E计算count=1
由A计算count=5
由D计算count=2
由C计算count=4

Process finished with exit code 0

本实验测试结果分析:尽管pirntln方法在内部是同步的,但i--的操作确是在进入println()之前发生的,所以有发生非线程安全的可能性

 /**
     * Prints a String and then terminate the line.  This method behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>String</code> to be printed.
     */
    public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
原文地址:https://www.cnblogs.com/edison20161121/p/7954557.html