Home » Java » Java multithreading (four) - coordinating synchron...

Java multithreading (four) - coordinating synchronous threads

when a thread uses some of the variables used in the synchronization method, and this variable needs other thread modifications to meet the requirements of this thread, then the wait () method.

can be used in the resynchronization method
When

uses the wait () method, the correct template is to place the lock in the while () loop,.


package test;
Public, class, TicketHome, implements, Runnable {
Int five_RMB = 2;
Int ten_RMB = 0;
Int twenty_RMB = 0;
@Override
Public, void, run () {
If (Thread.currentThread (),.GetName (),.Equals ("Mr.Z")) {
SaleTicket (20);
}
Else, if (Thread.currentThread (),.GetName (),.Equals ("Mr.S")) {
SaleTicket (5);
}
}
Public, synchronized, void, saleTicket (int, money) {
If (money = = 5) {
Five_RMB = five_RMB + 1;
System.out.println ("owe two," (+Thread.currentThread) (.GetName));
}
Else if (money = = 20) {
While (five_RMB<3) {
{try
System.out.println (too big to be found);
Wait ();
System.out.println ("got the money for you");
Catch (Exception E) {}}
}
Five_RMB = five_RMB - 3;
Twenty_RMB = twenty_RMB + 1;
System.out.println ("give" +Thread.currentThread ().GetName () + "admission ticket, retrieve $15";
}
NotifyAll
What are the differences between the /*notify method and the notifyAll method in terms of quantity?
NotifyAll causes all threads that have been waiting for the notify thread to quit wait on the object, waiting to be locked on the object, and once the object is unlocked, they compete
Notify he just choose a wait thread for notification, and make it get the lock on an object, but not to disturb the other is waiting for the same object notify thread, when the first thread running after releasing the lock on the object.
If the object does not have to use the notify statement again, even if the object has been idle, the other wait state waiting threads due to lack of notice of the object, to continue in the wait state, until the object sends a notify or notifyAll, they are waiting for is notify or notifyAll, but not the lock.
* /
}
}

The

annotation is quoted from the water column

http://blog.csdn.net/zhzwsjc1000/article/details/21518819


The

daemon thread means that when all user threads of the program has finished running, even if the daemon thread in the run () method is required in the statement execution, immediately daemon thread the end of the run. We can use the guardian for some not very important work. For example:


Thread.sleep (1000)


The

thread must set itself up before running, is it the daemon thread.

?

thread.setDaemon (true);

Latest