Deadlock definition
A deadlock is a situation in which two or more threads are permanently blocked, and the premise is to have two or more threads, and to operate two or more common resources; my understanding is that with two threads, an existing thread A and B operate both common resources A and b,a operation a when they are locked Locka , continue to execute, a also need to lockb do the following operation, this time B resources in the B thread operation, just be on the lock lockb, if at this time thread B just released lockb no problem, but did not release lockb lock, Threads A and B form the contention for the LOCKB lock resource, causing blocking to form a deadlock, with the following deadlock code:
Public class mydeadlocktest { Public Static voidMain (string[] args) {Object obj1 =NewObject (); Thread Thread1 =NewThread (NewDeadres (true, obj1)); Thread thread2 =NewThread (NewDeadres (false, obj1)); Thread1.start (); Thread2.start (); }} class deadres implements Runnable{ BooleanFlag Object obj; PublicDeadres (BooleanFlag, Object obj1) { This. flag = Flag; This. obj = obj1; } @Override Public voidRun () {if(flag) {synchronized (Deadres.class) {System.out.println (Thread.CurrentThread (). GetName () +"Acquie Lock is Deadres.class"); Synchronized (obj) {System.out.println (Thread.CurrentThread (). GetName () +"Acquie lock is obj"); } } }Else{synchronized (obj) {System.out.println (Thread.CurrentThread (). GetName () +"Acquie lock is obj"); Synchronized (Deadres.class) {System.out.println (Thread.CurrentThread (). GetName () +"Acquie Lock is Deadres.class"); } } } }}
Execution results such as:
Thread-1lockis objThread-0lockis DeadRes.class
Of course, each execution of the result is not the same, there may be a state of harmony, there is no deadlock, at this time to ensure that each deadlock, you can let the run () method to execute a while (true) loop, so that every time a deadlock must occur, of course, in practical applications, we should try to avoid deadlocks, Avoid synchronous nesting of the same lock object when multiple threads are working on several common resources.
Communication between Threads-producer and consumer patterns
1, let two threads alternately to operate, when the production of a number, immediately after the consumption of a, first adopted object object wait-notify to achieve, the specific code is as follows:
Public class threadproconsume { Public Static voidMain (string[] args) {Product Product =NewProduct (); Thread Thread1 =NewThread (NewProducer (product)); Thread thread2 =NewThread (NewConsumer (product)); Thread1.start (); Thread2.start (); }} class Product{String name;Private int Count=1;BooleanFlag =false; PublicSynchronizedvoidSet (String name) {if(flag) {Try{ This. Wait (); }Catch(Interruptedexception e) {E.printstacktrace (); } } This. Name = name +"--"+Count++; Flag =true; System.out.println (Thread.CurrentThread (). GetName () +"Produce num:"+ This. name); This. Notify (); } PublicSynchronizedvoidOut () {if(!flag) {Try{ This. Wait (); }Catch(Interruptedexception e) {E.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName () +"Consume num is:"+ This. name); Flag =false; This. Notify (); }} class Producer implements Runnable{Product Res; PublicProducer (product product) { This. res = product; } @Override Public voidRun () { while(true) {Res.set ("Guyue"); } }} class Consumer implements Runnable{Product Res; PublicConsumer (product product) { This. res = product; } @Override Public voidRun () { while(true) {res.out (); } }}
Execution results
thread-1ConsumeNumIs:guyue--3938thread-0ProduceNum: Guyue--3939thread-1ConsumeNumIs:guyue--3939thread-0ProduceNum: Guyue--3940thread-1ConsumeNumIs:guyue--3940thread-0ProduceNum: Guyue--3941thread-1ConsumeNumIs:guyue--3941
When more than two threads are operating, it is necessary to change the if judgment in the set () and Out () method to while and the Notif method to Notifyall (), so that when multiple threads operate, they can be alternately, with the following code:
Public classThreadproconsume { Public Static void Main(string[] args) {Product Product =NewProduct (); Thread Thread1 =NewThread (NewProducer (product)); Thread thread3 =NewThread (NewProducer (product)); Thread thread2 =NewThread (NewConsumer (product)); Thread thread4 =NewThread (NewConsumer (product)); Thread1.start (); Thread3.start (); Thread2.start (); Thread4.start (); }}class product{String name;Private intCount =1; Boolean flag =false; PublicSynchronizedvoid Set(String name) { while(flag) {Try{ This. Wait (); }Catch(Interruptedexception e) {E.printstacktrace (); } } This. Name = name +"--"+count++; Flag =true; System. out. println (Thread.CurrentThread (). GetName () +"Produce num:"+ This. name); This. Notifyall (); } PublicSynchronizedvoid out(){ while(!flag) {Try{ This. Wait (); }Catch(Interruptedexception e) {E.printstacktrace (); }} System. out. println (Thread.CurrentThread (). GetName () +"Consume num is:"+ This. name); Flag =false; This. Notifyall (); }}
The results of the implementation are as follows:
thread-0ProduceNum: Guyue--50325thread-2ConsumeNumIs:guyue--50325thread-1ProduceNum: Guyue--50326thread-3ConsumeNumIs:guyue--50326thread-0ProduceNum: Guyue--50327thread-2ConsumeNumIs:guyue--50327thread-1ProduceNum: Guyue--50328thread-3ConsumeNumIs:guyue--50328
2, using the Lock-condition method to achieve the following:
Class product{String name;Private intCount =1; Boolean flag =false; LockLock=NewReentrantlock (); Condition Conditon =Lock. Newcondition (); Public void Set(String name) {Try{Lock.Lock(); while(flag) {Conditon.await(); } This. Name = name +"--"+count++; Flag =true; System. out. println (Thread.CurrentThread (). GetName () +"Produce num:"+ This. name); Conditon.signalall (); }Catch(Exception e) { }finally{Lock. Unlock (); } } Public void out(){Try{Lock.Lock(); while(!flag) {Conditon.await(); } flag =false; System. out. println (Thread.CurrentThread (). GetName () +"Consumer num is:"+ This. name); Conditon.signalall (); }Catch(Exception e) { }finally{Lock. Unlock (); } }}
The results of the implementation are as follows:
thread-0ProduceNum: Guyue--20305thread-3ConsumerNumIs:guyue--20305thread-1ProduceNum: Guyue--20306thread-2ConsumerNumIs:guyue--20306thread-0ProduceNum: Guyue--20307thread-3ConsumerNumIs:guyue--20307thread-1ProduceNum: Guyue--20308thread-2ConsumerNumIs:guyue--20308
Simple case of Java multi-thread deadlock and inter-threading communication