Sync-Sync Lock-deadlock-thread interaction-Thread Synthesis example

Source: Internet
Author: User

One, synchronization

1. Role: To prevent multiple threads from accessing and modifying shared data at the same time for unsafe issues.

2. Use the synchronized (object) {} method.

Second, the mechanism

1. The thread must obtain a "Sync lock object" before the thread enters a code that is locked by a "sync lock"

2. Ensure that only one thread can execute the locked code at any time

3. Do not use "competing resources" as "synchronization objects"

Third, the release of the synchronous lock

1. Code completion

2. Statement block throws an exception

3. Statement block encountered Break,return

4. Call the Wait method

5. Note: The sleep and yield methods do not release the sync lock

Four, Object lock pool

New->start (), Running <---Scheduling task--running->run () Finish-end

Running---blocking events (sleep,join)-----> blocking-----Unblocking----> operational

A lock pool for------> Blocked objects that are running---synchronization-----get----> can run

Five, the Code demonstration
 Packagesynchronization; Public classCounerImplementsrunnable{Private intcounter=200;  Public voidrun () { for(inti = 0;i<50;i++){            synchronized( This) {counter-=2; Try{Thread.Sleep (10);}Catch(Interruptedexception e) {} System.out.print (counter+"   "); }        }                    }}
 Package synchronization;  Public class TESTCOUNERSYC {    publicstaticvoid  main (string[] args) {          New  Couner ();         New Thread (c);         New Thread (c);        T1.start ();        T2.start ();    }}
Six, deadlock

1. Definition: Two threads are waiting for the other party to execute before the deadlock occurs, into the infinite wait.

2. Workaround: Specify the order in which locks are acquired and force threads to acquire locks in the order specified.

3. Dead-Lock Code case

 Packagedeadlock; Public classdeadlock{Private FinalObject left =NewObject (); Private FinalObject right =NewObject ();  Public voidLeftRight ()throwsException {synchronized(left) {Thread.Sleep (2000); synchronized(right) {System.out.println ("LeftRight end!"); }        }    }         Public voidRightleft ()throwsException {synchronized(right) {Thread.Sleep (2000); synchronized(left) {System.out.println ("Rightleft end!"); }        }    }}
 Packagedeadlock; Public classThread0extendsthread{PrivateDeadLock DL;  PublicThread0 (DeadLock dl) { This. DL =DL; }         Public voidrun () {Try{dl.leftright (); }         Catch(Exception e) {e.printstacktrace (); }    }}
 Packagedeadlock; Public classThread1extendsthread{PrivateDeadLock DL;  PublicThread1 (DeadLock dl) { This. DL =DL; }         Public voidrun () {Try{dl.rightleft (); }         Catch (Exception e) {e.printstacktrace (); }    }}
 Package deadlock;  Public class Test {    publicstaticvoid  main (string[] args)    {        new  DeadLock ();         New Thread0 (DL);         New Thread1 (DL);        T0.start ();        T1.start ();          while (true);}       }

Vii. Thread Interaction

The 1.wait method causes the thread to go into a blocking state until the thread gets a wake-up notification or reaches the specified time.

Attention:

1) The wait and notify methods can only be called within the synchronization block of the object being accessed.

2) When a thread calls the Wait method to enter the waiting state, the object lock token is freed.

2. Wake-up mode

Notification Wakeup-notify or Notifyall method

Active wakeup-reaching blocking events

Interrupt Wakeup-The interrupt method is called by another thread, and a Interruptedexception exception is received.

3. Code Demo

 Packagethread interaction; Public classCounerImplementsrunnable{Private intCounter=0;  Public voidSetcounter (intcounter) {         This. Counter =counter; }         Public synchronized voidrun () {if(counter<100){            Try {                 This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} counter-=100; System.out.println ("Counter =" +counter); System.out.println ("Counter Thread End"); }}

 Packagethread interaction; Public classtestcounerwait { Public Static voidMain (string[] args) {Couner C=NewCouner (); Thread T=NewThread (c);                T.start (); Try{Thread.Sleep (1000); } Catch(Interruptedexception e) {}synchronized(c) {C.setcounter (150);        C.notify (); } System.out.println ("Main Thread End"); }}

Viii. Thread Synthesis Example (code)

 Packagethread synthesis example; Public classcouner{Private intCounter=0;  Public synchronized intIncrease (intN) {Counter+=N;  This. Notify (); System.out.printf ("Production: couner=%-2d n=%-2d\n", Counter,n); returncounter; }             Public synchronized intDecrease (intN) {         while(counter<N) {            Try {                 This. Wait (); } Catch(Interruptedexception e) {}} counter-=N; System.out.printf ("Consumption: couner=%-2d n=%-2d\n", Counter,n); returncounter; }    }

 Packagethread synthesis example; Public classProducerImplementsrunnable{PrivateCouner Couner;  PublicProducer (Couner couner) { This. Couner =Couner; }         Public voidrun () { for(inti=0;i<50;i++) {couner.increase (int) (Math.random () *10)); Try{Thread.Sleep (int) (Math.random () *100)); } Catch(interruptedexception e) {e.printstacktrace (); }                                }    }        }

 Packagethread synthesis example; Public classConsumerImplementsrunnable{PrivateCouner Couner;  PublicConsumer (Couner couner) { This. Couner =Couner; }         Public voidrun () { for(inti=0;i<50;i++) {couner.decrease (int) (Math.random () *8)); Try{Thread.Sleep (int) (Math.random () *100)); } Catch(interruptedexception e) {e.printstacktrace (); }                                }    }        }

 Packagethread synthesis example; Public classTESTPC { Public Static voidMain (string[] args) {Couner Couner=NewCouner (); Producer P=NewProducer (Couner); Thread T1=NewThread (P); Consumer C=NewConsumer (Couner); Thread T2=NewThread (c);        T1.start ();    T2.start (); }}

Sync-Sync Lock-deadlock-thread interaction-Thread Synthesis example

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.