The security and resolution mechanism of Java multithreading thread

Source: Internet
Author: User

What are the causes of thread safety problems? There is a security issue with shared data because one thread is involved in the process of sharing data while the other thread is not finished executing

 PackageCom.atguigu.java; Public classTestWindow1 { Public Static voidMain (string[] args) {Window W=NewWindow (); Thread T1=NewThread (W); Thread T2=NewThread (W); T1.setname ("Window 1"); T2.setname ("Window 2");        T1.start ();    T2.start (); }}classWindowImplementsRunnable {intTicket = 50;  Public voidrun () { while(true) {            if(Ticket > 0) {                Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); } Else {                 Break; }        }    }}
One of the running results:

Window 1 Ticketing, ticket no: 50
Window 2 Ticketing, ticket no: 49
Window 1 Ticketing, ticket no: 48
Window 2 Ticketing, ticket no: 47
Window 2 Ticketing, ticket no: 46
Window 1 Ticketing, ticket no: 45
Window 2 Ticketing, ticket no: 43
Window 1 Ticketing, ticket no: 44
Window 1 Ticketing, ticket no: 42
Window 2 Ticketing, ticket no: 41
Window 2 Ticketing, ticket no: 40
Window 1 Ticketing, ticket no: 39
Window 2 Ticketing, ticket no: 38
Window 1 Ticketing, ticket no: 38
Window 2 Ticketing, ticket no: 37
Window 1 Ticketing, ticket no: 36
Window 1 Ticketing, ticket no: 34
Window 2 Ticketing, ticket no: 35
Window 2 Ticketing, ticket no: 33
Window 1 Ticketing, ticket no: 32
Window 2 Ticketing, ticket no: 31
Window 1 Ticketing, ticket no: 31
Window 2 Ticketing, ticket no: 30
Window 1 Ticketing, ticket no: 29
Window 2 Ticketing, ticket no: 28
Window 1 Ticketing, ticket no: 27
Window 2 Ticketing, ticket no: 26
Window 1 Ticketing, ticket no: 26
Window 1 Ticketing, ticket no: 25
Window 2 Ticketing, ticket no: 24
Window 1 Ticketing, ticket no: 23
Window 2 Ticketing, ticket no: 22
Window 1 Ticketing, ticket no: 21
Window 2 Ticketing, ticket no: 20
Window 1 Ticketing, ticket no: 19
Window 2 Ticketing, ticket no: 19
Window 1 Ticketing, ticket no: 18
Window 2 Ticketing, ticket no: 17
Window 2 Ticketing, ticket no: 15
Window 1 Ticketing, ticket no: 16
Window 1 Ticketing, ticket no: 14
Window 2 Ticketing, ticket no: 13
Window 1 Ticketing, ticket no: 12
Window 2 Ticketing, ticket no: 11
Window 1 Ticketing, ticket no: 10
Window 2 Ticketing, ticket no: 9
Window 2 Ticketing, ticket no: 8
Window 1 Ticketing, ticket no: 8
Window 2 Ticketing, ticket no: 7
Window 1 Ticketing, ticket no: 6
Window 1 Ticketing, ticket no: 4
Window 2 Ticketing, ticket no: 5
Window 2 Ticketing, ticket no: 3
Window 1 Ticketing, ticket no: 2
Window 2 Ticketing, ticket no: 0
Window 1 Ticketing, ticket no: 1

Can be found in the results of the operation of the number of votes and votes in the case of 0

How do I fix a thread's security problem? You must have one thread operation to share the data, and other threads have the opportunity to participate in the shared data operation.

Java implements thread security in one: Synchronized keyword, thread synchronization

1) Synchronizing code blocks           

 PackageCom.atguigu.java;
//Implement Runnable interface classWindowImplementsRunnable {intTicket = 50;//Sharing Data Public voidrun () { while(true) {
//Note: In the way of implementation, consider synchronization, you can use this to act as a lock. But in the way of inheritance, use this! with caution. synchronized( This) {//This represents the current object, which is W if(Ticket > 0) { Try{Thread.CurrentThread (). Sleep (10); } 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); T1.setname ("Window 1"); T2.setname ("Window 2"); T1.start (); T2.start (); }}
 PackageCom.atguigu.java; //Inherit the thread class classWindowextendsThread {Static intTicket = 100; StaticObject obj =NewObject ();  Public voidrun () { while(true) {            synchronized(obj) {if(Ticket > 0) {                    Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); }            }        }    }    } Public classTestwindow { Public Static voidMain (string[] args) {Window W1=NewWindow (); Window W2=NewWindow (); W1.setname ("Window 1"); W2.setname ("Window 2");        W1.start ();    W2.start (); }}

2) Synchronization method

Package Com.atguigu.java;
ClassWindowImplementsRunnable {intticket = 100;//Sharing Data Public voidrun () { while(true) {show (); } } Public synchronized voidShow () {if(Ticket > 0) { Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.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); T1.setname ("Window 1"); T2.setname ("Window 2"); T1.start (); T2.start (); }}

Java implements thread security mode two: Lock

 PackageCom.yyx.thread;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classTestlock { Public Static voidMain (string[] args) {Window W=NewWindow (); Thread T1=NewThread (W); Thread T2=NewThread (W); T1.setname ("Window 1"); T2.setname ("Window 2");          T1.start ();      T2.start (); }}//implementing the Runnable interfaceclassWindowImplementsRunnable {intticket = 100;//Sharing DataLock lock=NewReentrantlock ();  Public voidrun () { while(true) {             Try{lock.lock (); if(Ticket > 0) {                     Try{Thread.CurrentThread (). Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "Ticketing, ticket:" + ticket--); }            } Catch(Exception ex) {}finally{lock.unlock (); }                    }  }}

The security and resolution mechanism of Java multithreading thread

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.