Thread Unsafe code Testing
private static class UnsafeSequence { private int value; public int getNext() { return value++; } }
Using two threads to invoke the above GetNext method 1000 times, there is a thread unsafe situation, in the results of the turn out there are two 1311:
Picture. png
Cause analysis, consistent with what the book says:
Picture. png
The complete code
Import Java.io.PrintWriter;Import Java.util.concurrent.CountDownLatch;/** * Created by luohao07 on 2018/1/2. */PublicClassunsafesequencetest {PublicStaticvoidMain(string[] args)Throws exception{unsafesequence unsafesequence =New Unsafesequence (); PrintWriter out =New PrintWriter ("OUT.txt"); Countdownlatch Countdownlatch =New Countdownlatch (2);New Thread () {@OverridePublicvoidRun() {for (int i =0; I <1000; i++) {out.println (Unsafesequence.getnext () +"T1"); } countdownlatch.countdown (); }}.start ();New Thread () {@OverridePublicvoid 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 performs timed tasks
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)); }}
The program starts 5 seconds after the output invoke ....
Welcome to join the Learning Exchange Group 569772982, we learn to communicate together.
Java concurrent Programming Combat Chapter I