场景:有2个线程,当第一个线程执行到5的时候,第二个线程结束,第二个线程结束后,第一个线程继续执行。
package mashibing;
/**
* wait释放锁
* notifyAll不释放锁,所以调用完notifyAll还要再加一个wait才能让当前线程释放锁。
* sleep也不释放锁。
*/
import java.util.concurrent.TimeUnit;
public class MyContainer1 {
int count=0;
public synchronized void m1() {
for (int i = 0; i < 10; i++) {
System.out.println("m1 "+i);
count++;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if(count==5) {
try {
notifyAll();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
notifyAll();
}
public synchronized void m2() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (count!=5) {
System.out.println("m2 start");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("m2 end");
notifyAll();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MyContainer1 c=new MyContainer1();
new Thread(new Runnable() {
@Override
public void run() {
c.m2();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
c.m1();
}
}).start();
}
}