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 }
结果如下
D:\it\jdk1.8\bin\java -Didea.launcher.port=7540 "-Didea.launcher.bin.path=D:\it\idea\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\it\jdk1.8\jre\lib\charsets.jar;D:\it\jdk1.8\jre\lib\deploy.jar;D:\it\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\it\jdk1.8\jre\lib\ext\cldrdata.jar;D:\it\jdk1.8\jre\lib\ext\dnsns.jar;D:\it\jdk1.8\jre\lib\ext\jaccess.jar;D:\it\jdk1.8\jre\lib\ext\jfxrt.jar;D:\it\jdk1.8\jre\lib\ext\localedata.jar;D:\it\jdk1.8\jre\lib\ext\nashorn.jar;D:\it\jdk1.8\jre\lib\ext\sunec.jar;D:\it\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\it\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\it\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\it\jdk1.8\jre\lib\ext\zipfs.jar;D:\it\jdk1.8\jre\lib\javaws.jar;D:\it\jdk1.8\jre\lib\jce.jar;D:\it\jdk1.8\jre\lib\jfr.jar;D:\it\jdk1.8\jre\lib\jfxswt.jar;D:\it\jdk1.8\jre\lib\jsse.jar;D:\it\jdk1.8\jre\lib\management-agent.jar;D:\it\jdk1.8\jre\lib\plugin.jar;D:\it\jdk1.8\jre\lib\resources.jar;D:\it\jdk1.8\jre\lib\rt.jar;F:\springboot\threaddemo\out\production\threaddemo;D:\it\idea\IntelliJ IDEA 2016.3.3\lib\idea_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(); } }