Personal notes-multithreading (Security and communication)

Source: Internet
Author: User
Tags dateformat instance method windows 5

Thread safety issues:

Because multiple threads are working on shared data, and multiple statements are operating on shared data, multithreading security issues are generated, resulting in a synchronized code block.

Prerequisites for synchronization:

Minimum of two threads. You must ensure that the same lock is used.

Add: Multiple start () the same thread is illegal.

is SimpleDateFormat thread-safe?

SimpleDateFormat is not thread-safe. The user should create a separate instance for each thread. Formatting the same time, if the formatted result is inconsistent or throws an exception, it proves that SimpleDateFormat is indeed thread insecure.

Example:

 Public classSimpledateformattest { Public Static voidMain (string[] args) {SimpleDateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String DateTime= "2016-12-30 15:35:34";  for(inti = 0; I < 5; i++) { NewThread (NewRunnable () {@Override Public voidrun () { for(inti = 0; I < 5; i++) { Try{System.out.println (Thread.CurrentThread (). GetName ()+ "\ T" +Dateformat.parse (dateTime)); } Catch(ParseException e) {e.printstacktrace ();}} }}). Start (); } } }

Run results (slightly)

Conclusion:

It can be found that not only the exception is thrown, but the printed result is inconsistent. It seems that SimpleDateFormat is not thread-safe.

You can see a member variable in SimpleDateFormat's parent class DateFormat, which says that the calendar is used for formatting and parsing.

In addition, because the calendar as a member variable, in the multi-threaded scenario, there will be inconsistent resource sharing problems. This is why the SimpleDateFormat thread is unsafe.

How to avoid:

Use Threadlocal to store SimpleDateFormat. The threadlocal feature determines the value in each thread's operation threadlocal and does not affect other threads.

Threadlocal is a class for creating thread-local variables.

In general, the variables we create can be accessed and modified by any one thread. Variables created with threadlocal can only be accessed by the current thread and other threads cannot be accessed and modified.

What are the characteristics of synchronous code blocks and synchronization functions?

A lock used by a synchronization code block can be any object (but not an anonymous object). The lock used by the synchronization function (which is synchronized decorated on the method) is this, and the lock of the static synchronization function is the bytecode file object of the class.

There is only one synchronization in a class, and you can use synchronous functions. If you have multiple synchronizations, you must use a synchronous code block to determine the different locks. So the synchronization code block is relatively flexible.

Inter-thread communication:

Idea: Multiple threads are manipulating the same resource, but the action is different.

Encapsulates a resource as an object. The task that the thread performs (the task is actually the Run method) is also encapsulated as an object.

Wait for wake-up mechanism:

Wait: The thread in the synchronization is frozen. Release the executive right and release the eligibility. Store thread objects in the thread pool at the same time. Notify: Wakes one of the waiting threads in the thread pool. Notifyall: All threads in the thread pool are awakened.

Wait and sleep differences:

Wait: You can specify a time or you can not specify a time. No time is specified and can only be awakened by the corresponding notify or Notifyall. Sleep: The time must be specified to automatically turn from the frozen state to the running state (temporary blocking state). Wait: The thread releases the execution and the thread releases the lock. Sleep: The thread releases the execution, but does not release the lock.

Q: What happens when I use synchronization on a static method?

A: When a static method is synchronized, it gets the "Class" Object of the class, so when a thread enters a synchronous static method,

Thread monitor Gets the object lock of the class itself, and other threads cannot enter any static synchronization methods for this class.

Q: When a synchronous method has been executed, can a thread invoke a non-synchronous instance method on an object?

A: Yes, a non-synchronous method can always be called without any problems.

Example 1:

/*** Three teachers, send 80 papers, ask each teacher to take turns.*/ Public classTest04 { Public Static voidMain (string[] args) {FinalPaper p =NewPaper (); NewThread ("Miss Zhang") {             Public voidrun () {Try{p.send1 (); } Catch(interruptedexception e) {e.printstacktrace ();        }            };                }.start (); NewThread ("Miss Gong") {             Public voidrun () {Try{p.send2 (); } Catch(interruptedexception e) {e.printstacktrace ();        }            };                }.start (); NewThread ("Teacher Liu") {             Public voidrun () {Try{p.send3 (); } Catch(interruptedexception e) {e.printstacktrace ();        }            };    }.start (); }}classPaper {Private intPaper = 80; Private intFlag = 1;  Public voidSend1 ()throwsinterruptedexception { while(true) {            synchronized( This) {                 while(Flag! = 1) {                     This. Wait (); }                if(paper = = 0) {flag= 2;  This. Notifyall ();  Break; } System.out.println (Thread.CurrentThread (). GetName ()+ "sent the first" + paper--+ "papers"); Flag= 2;  This. Notifyall (); }        }    }     Public voidSend2 ()throwsinterruptedexception { while(true) {            synchronized( This) {                 while(Flag! = 2) {                     This. Wait (); }                if(paper = = 0) {flag= 3;  This. Notifyall ();  Break; } System.out.println (Thread.CurrentThread (). GetName ()+ "sent the first" + paper--+ "papers"); Flag= 3;  This. Notifyall (); }        }    }     Public voidSend3 ()throwsinterruptedexception { while(true) {            synchronized( This) {                 while(Flag! = 3) {                     This. Wait (); }                if(paper = = 0) {flag= 1;  This. Notifyall ();  Break; } System.out.println (Thread.CurrentThread (). GetName ()+ "sent the first" + paper--+ "papers"); Flag= 1;  This. Notifyall (); }        }    }}

Example 2:

/**sum = from 1 to 10 and + from 11 to 20 and * Write 10 threads, the first thread from 1 to 10, the second thread from 11 to 20, ..., * Tenth thread from 91 to 100, and then add the results of 10 threads to the console*/ Public classTest05 { Public Static voidMain (string[] args)throwsinterruptedexception { for(inti = 0; I < 10; i++) {Xiangjia XJ=NewXiangjia (); Xj.setname ("Thread" + (i + 1)); Xj.setinit (i* 10);        Xj.start (); } thread.sleep (10); }}classXiangjiaextendsThread {Static intTotal ; intInti;  Public voidSetinit (intinti) {         This. Inti =Inti; } @Override Public voidrun () {synchronized(Xiangjia.class) {            intsum = 0;  for(inti = 1; I <= 10; i++) {sum+ = Inti +i; } Total+=sum; System.out.println (GetName ()+ "... total=" +Total ); }    }}

Example 3:

/*** A bun shop business is hot, now open 5 window simulation selling 100 buns, each time each window randomly sold 1-5 buns, sold out the last bun after the tip "buns have sold" (must all sold), the program ends.*/ Public classTest06 { Public Static voidMain (string[] args) {Baozi Bz1=NewBaozi ("Windows 1"); Baozi bz2=NewBaozi ("Windows 2"); Baozi bz3=NewBaozi ("Windows 3"); Baozi bz4=NewBaozi ("Windows 4"); Baozi Bz5=NewBaozi ("Windows 5");        Bz1.start ();        Bz2.start ();        Bz3.start ();        Bz4.start ();    Bz5.start (); }}classBaoziextendsThread {baozi (String str) {Super(str); }    //Total Buns    Static intBaozi = 100; Random R=NewRandom (); @Override Public voidrun () { while(true) {            synchronized(Baozi.class) {                if(Baozi <= 0) {                     Break; }                Try{Thread.Sleep (30); } Catch(interruptedexception e) {e.printstacktrace (); }                intNextint = R.nextint (5) + 1; if(Baozi <= Nextint) {//at this time buns have been sold to less than 5Nextint =Baozi; System.out.println ( This. GetName () + "SOLD" + Nextint + "one"); System.out.println ("Buns have been sold OUT!!!!"); } Else {                    //at this time the bun is more than 5System.out.println ( This. GetName () + "SOLD" + Nextint + "one"); } Baozi-=Nextint;            System.out.println (Baozi); }        }    }}

Personal notes-multithreading (Security and communication)

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.