子线程循环10次,接着主线程循环10,接着又回到子线程循环10次,接着再回到主线程又循环10,如此循环5次
public class ThreadTest{
public boolean first = true;//空值顺序, important
public synchronized void subTask() throws InterruptedException{
for(int i=0; i<5; i++){
if(!first)
this.wait();
for(int j=0; j<10; j++){
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSS j = "+j);
}
first = false;
this.notify();
// Thread.sleep(2000);
}
}
public synchronized void mianTask() throws InterruptedException{
System.out.println("mainTask");
for(int i=0; i<5; i++){
if(first){
this.wait();
}
for(int j=0; j<10; j++){
System.out.println("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm j = "+j);
}
first = true;
this.notify();
}
}
public static void main(String [] args) throws InterruptedException{
final ThreadTest test = new ThreadTest();
new Thread(new Runnable(){
@Override
public void run() {
try {
test.subTask();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
test.mianTask();
}
}
notify()告诉等待当前锁的线程, 你们可能得到一个锁资源, 但是只有在执行wait()释放当前锁资源之后, 其他等待当前锁的线程才会获得锁并且执行。
下面程序说明了, 只有在调用一次notify(), 然后再调用一次wait()之后, 才会唤醒mainTask, 不论中间执行了多少操作, 或者等待了多长时间。
public class ThreadTest{
public boolean first = true;//空值顺序, important
public synchronized void subTask() throws InterruptedException{
for(int i=0; i<5; i++){
System.out.println("i = "+i);
if(!first&&i%2==0){
System.out.println("wait()");
this.wait();
}
for(int j=0; j<10; j++){
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSS j = "+j);
}
first = false;
if(i%2==0){
System.out.println("notify()");
this.notify();
}
// Thread.sleep(2000);
}
}
public synchronized void mianTask() throws InterruptedException{
System.out.println("mainTask");
for(int i=0; i<5; i++){
if(first){
this.wait();
}
for(int j=0; j<10; j++){
System.out.println("mmmmmmmmmmmmmmmmmmmmmmmmmmmmm j = "+j);
}
first = true;
this.notify();
}
}
public static void main(String [] args) throws InterruptedException{
final ThreadTest test = new ThreadTest();
new Thread(new Runnable(){
@Override
public void run() {
try {
test.subTask();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
test.mianTask();
}
}