Java Day 14

Source: Internet
Author: User

Multithreading--Inter-thread communication
Handle the same resource, but the task is different

Inter-thread communication-waiting for wake-up mechanism
1, wait (); Thread is in a frozen state, and the wait thread is stored in the inline pool
2, notify (); Wake a thread from a thread pool
3, Notifyall (); Wake All Threads
method must be defined in the synchronization

Why the method of manipulating threads wait notify Notifyall defined in the object class
Because these methods are the monitor's method, the monitor is actually the lock
A lock can be any object, and the way an arbitrary object is called must be defined in the object class.

Wake-Up-code optimization

Multi-producer and multi-consumer

Multi-production Multi-consumer problem solving
Notifyall ();

While judgment flag, resolves whether the thread will run again after getting execution

notifyall () resolves the thread of this party must wake the other thread

JDK1.5 new feature of multi-production and multi-consumption problem--lock
The synchronous code block, which is implicit for the operation of the lock.

1 Importjava.util.concurrent.locks.*;2 //import java.util.condition;3 classresource{4     PrivateString name;5     Private intCount = 1;6     Private BooleanFlag =false;7Lock lock =NewReentrantlock ();8     //Condition C1 = lock.newcondition ();9Condition Pro_con =lock.newcondition ();TenCondition Cos_con =lock.newcondition (); One      A Resource () {} -      -      Public voidSet (String name) {//synchronized the Lock.lock (); -         Try{ -              while(flag)//While (flag)--Deadlock -                 //try{wait ();} catch (Interruptedexception e) {} +                 Try{pro_con.await ();}Catch(Interruptedexception e) {} -              This. Name = name +count; +count++; ASystem.out.println (Thread.CurrentThread (). GetName () + ": production. 5.0. "+ This. Name); atFlag =true; -             //Notifyall ();//Notifyall () -             //C1.signalall ();//Notifyall () -Cos_con.signal ();//Notifyall () -         } -         finally{ in Lock.unlock (); -         } to          +          -     } the      *      Public  voidOut () {//synchronized $ Lock.lock ();Panax Notoginseng         Try{ -              while(!flag)//While (flag)--deadlock--notifyall () the                 Try{cos_con.await ();}Catch(Interruptedexception e) {} +System.out.println (Thread.CurrentThread (). GetName () + ": ... Consumption of ... "+name); AFlag =false; the             //Notifyall ();//notifyall ()} +             //C1.signalall (); - pro_con.signal (); $              $         } -         finally{ -Lock.unlock ();//Notifyall () the         }     -     }Wuyi } the  - classProducerImplementsrunnable{ Wu     PrivateResource R; - Producer (Resource r) { About          This. R =R; $     } -  -      Public voidrun () { -          while(true){ AR.set ("Roast Duck"); +         } the          -     } $ } the  the classConsumerImplementsrunnable{ the     PrivateResource R; the Consumer (Resource r) { -          This. R =R; in     } the      Public voidrun () { the          while(true){ About r.out (); the         }     the     } the } +  - classproduceconsumerdemo{ the      Public Static voidMain (string[] args) {BayiResource r =NewResource (); theProducer Pro =NewProducer (r); theConsumer con =NewConsumer (r); -          -Thread T0 =NewThread (pro); theThread T1 =NewThread (pro); theThread t2 =NewThread (con); theThread t3 =NewThread (con); the          - T0.start (); the T1.start (); the T2.start (); the T3.start ();94          the     } the}
View Code


Encapsulates synchronization and locks into objects

JDK1.5 new Features--condition
Wait Notify Notifyall

JDK1.5 Workaround
One lock multiple monitors

Example
Lock interface: Replaces a synchronous code block or synchronization function, which is changed from an implicit lock operation to a display
Lock () Get locks
Unlock () release lock in finally code block

The Condition interface replaces the wait Notify Notifyall method in object, which is encapsulated separately
Await
Signal
Signalall

1  classBoundedbuffer {2    FinalLock lock =NewReentrantlock ();3    FinalCondition Notfull =lock.newcondition ();4    FinalCondition Notempty =lock.newcondition ();5 6    Finalobject[] Items =Newobject[100];7    intputptr, Takeptr, Count;8 9     Public voidPut (Object x)throwsinterruptedexception {Ten Lock.lock (); One      Try { A         while(Count = =items.length) - notfull.await (); -ITEMS[PUTPTR] =x; the        if(++putptr = = items.length) putptr = 0; -++count; - notempty.signal (); -}finally { + Lock.unlock (); -      } +    } A  at     PublicObject Take ()throwsinterruptedexception { - Lock.lock (); -      Try { -         while(count = = 0) - notempty.await (); -Object x =Items[takeptr]; in        if(++takeptr = = items.length) takeptr = 0; ---count; to notfull.signal (); +        returnx; -}finally { the Lock.unlock (); *      } $    }Panax Notoginseng}
View Code

Wait Sleep Difference
1, wait can specify the time or can not be specified, sleep must specify
2, in the synchronization, the implementation of the CPU and the lock processing different
Wait release execution and lock
Sleep release execution is not a release lock

Stop Threading Mode--Define Tags
1. Stop method
2. End of Run method
How does the task of controlling threads end?
Control loops to end tasks

Stop Threading Mode--interrupt
If the thread is in a frozen state and cannot read the tag, how does it end?
Interrupt a thread from a freeze to a running state, but an interrupt exception occurs

Daemon Process--setdaemon
A background thread that is called before the thread starts

Join method
SetPriority (thread.max_priority)

Yield

Java Day 14

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.