Java concurrent Programming Combat Chapter I

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.