<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Memory + + 2vM/memory/J0tTLzbXEs/memory + PGJyPgo8L3A + CjxwPiAgMi6/memory + ICAgIL2ryc/memory "http://www.2cto.com/uploadfile/Collfiles/20141225/20141225085457277.jpg" alt = "\">
After consideration, I sent the Big Apple to the goddess alone.
However, due to the different locations of sleep and Synchronized, there are many different results, which are worth studying:
Scenario 1:
Public void run () {try {for (int I = 0; I <10; I ++) {synchronized (this) {Thread. sleep (1000); if (apple> 0) {System. out. println (Thread. currentThread (). getName () + ":" + apple -- + "apple") ;}}} catch (Exception e ){}}Result:
I am sending apples all by myself. Alas, it hurts. Think about it carefully. This sleep writing is actually the same as not writing. You are asleep, and other buddies are sleeping.
Case 2:
Public void run () {try {synchronized (this) {for (int I = 0; I <10; I ++) {Thread. sleep (1000); if (apple> 0) {System. out. println (Thread. currentThread (). getName () + ":" + apple -- + "apple") ;}}} catch (Exception e ){}}
This is similar to the case 1 and continues to hurt. Because the lock is to let me finish sending 10 apples by myself.
Case 3
Public void run () {try {for (int I = 0; I <10; I ++) {Thread. sleep (1000); if (apple> 0) {synchronized (this) {System. out. println (Thread. currentThread (). getName () + ":" + apple -- + "apple") ;}}} catch (Exception e ){}}
Result:
You see, there are no more apples. Two other color wolves keep sending apples. This is because when Li Yi sent the last apple, the two products thought there was an apple (which has already been determined to be an apple> 0), So he continued to send the product, as a result, I gave my apple to my sister.
Scenario 4
Public static void main (String [] args) {// four people start sending Apple RunnableTest runnableTest1 = new RunnableTest (); RunnableTest runnableTest2 = new RunnableTest (); runnableTest runnableTest3 = new RunnableTest (); (new Thread (runnableTest1, "Li Yi ")). start (); (new Thread (runnableTest1, "Shen 2 ")). start (); (new Thread (runnableTest1, "Wang San ")). start (); (new Thread (runnableTest1, "Game 4 ")). start ();}Result:
Four people want to send 10 apples by themselves. This is really a wolf in the dormitory. This is the most obvious mistake, although I found the problem for a long time.
What is the lock? Locks resources under an object. Case 4 consists of three objects and cannot be locked.