Java Multithreading thread Security

Source: Internet
Author: User

1. What is a thread safety issue?

A thread-safety issue occurs for the current thread if an Access object is modified by another thread from the beginning of a thread's access to the end of the access process;

If no object is modified by another thread throughout the access process, it is thread-safe.

2. Root cause of thread safety issues

The first is the multi-threaded environment, that is, there are multiple operators at the same time, the single-threaded environment does not have a thread safety problem. In a single-threaded environment, any operation, including modifications, is made by the operator himself,

The operator does not only have a definite purpose when issuing the operation, but also realizes the influence of the operation.

Multiple operators (threads) must manipulate the same object, and only multiple operators can manipulate one object at a time, and the effect of the behavior is immediately passed on to the other operator.

The actions of multiple operators (threads) on the same object must include a modification operation, common read no thread safety issues, because the object is not modified, has not changed, and cannot have an impact.

In summary, the root cause of thread safety problems is the possibility that shared data is being modified concurrently, that is, when one thread reads, another thread is allowed to modify

See Example: Analog Train station ticketing window, open three-window ticketing, total votes of 100

Example one:

 Packagecom.yyx.test;//simulated train station ticketing window, open three-window ticketing, total number of tickets is 100//a thread-safe issue existsclassWindowextendsThread {Static intTicket = 100;  Public voidrun () { while(true) {            if(Ticket > 0) {                Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); } Else {                 Break; }        }    }} Public classTestwindow { Public Static voidMain (string[] args) {Window W1=NewWindow (); Window W2=NewWindow (); Window W3=NewWindow (); W1.setname ("Window 1"); W2.setname ("Window 2"); W3.setname ("Window 3");        W1.start ();        W2.start ();    W3.start (); }}

Example two:

 Packagecom.yyx.test;//using the Runnable interface method, the ticketing/** This program has a thread security issue: When printing tickets, there will be a heavy ticket, the wrong ticket*/classWindow1ImplementsRunnable {intTicket = 100;  Public voidrun () { while(true) {            if(Ticket > 0) {                Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); } Else {                 Break; }        }    }} Public classTestWindow1 { Public Static voidMain (string[] args) {Window1 W=NewWindow1 (); Thread T1=NewThread (W); Thread T2=NewThread (W); Thread T3=NewThread (W); T1.setname ("Window 1"); T2.setname ("Window 2"); T3.setname ("Window 3");        T1.start ();        T2.start ();    T3.start (); }}

3. Thread-Safe resolution

you must have one thread operation to share the data, and other threads have the opportunity to participate in the shared data operation.

1) thread synchronization mechanism synchronized

Synchronizing code blocks

 Packagecom.yyx.test;/*Sync code block * synchronized (Sync monitor) {*//code block that needs to be synchronized (i.e. code to share data for operation) *} * 1. Shared data: Multiple threads working together The same data (variable) * 2. Synchronization monitor: An object of a class acts as a. Which thread gets this monitor, who executes the code that is synchronized in curly braces. Commonly known as: Lock * Requirements: All threads must share the same lock! * Note: In the way of implementation, if you consider synchronization, you can use this to act as a lock. But in the way of inheritance, use this! with caution. */classWindowImplementsRunnable {intTicket = 50;//Sharing Data     Public voidrun () { while(true) {            //This represents the current object, which is W            synchronized( This) {                if(Ticket > 0) {                    Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); }            }        }    }} Public classTestwindow { Public Static voidMain (string[] args) {Window W=NewWindow (); Thread T1=NewThread (W); Thread T2=NewThread (W); Thread T3=NewThread (W); T1.setname ("Window 1"); T2.setname ("Window 2"); T3.setname ("Window 3");        T1.start ();        T2.start ();    T3.start (); }}

Synchronization method

 Packagecom.yyx.test;/** Synchronization method declares the method that operates the shared data as synchronized. That is, this method is a synchronous method that guarantees that when one of the threads executes * This method, other threads wait outside until this thread finishes executing this method*/classWindowImplementsRunnable {intTicket = 50;//Sharing Data     Public voidrun () { while(true) {show (); }    }     Public synchronized voidShow () {if(Ticket > 0) {            Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); }    }} Public classTestwindow { Public Static voidMain (string[] args) {Window W=NewWindow (); Thread T1=NewThread (W); Thread T2=NewThread (W); Thread T3=NewThread (W); T1.setname ("Window 1"); T2.setname ("Window 2"); T3.setname ("Window 3");        T1.start ();        T2.start ();    T3.start (); }}

Java Multithreading thread Security

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.