//子线程循环10次,接着主线程循环100次,接着在子线程循环10次,接着再主线程循环100次
public class SynTest {
public static void main(String[] args) {
final Business b=new Business();
new Thread(
new Runnable(){
@Override
public void run() {
for(int i=1;i<=50;i++){
b.sub();
}
}
}).start();
new Thread(
new Runnable(){
@Override
public void run() {
for(int i=1;i<=50;i++){
b.main();
}
}
}).start();
}
}
class Business {
private boolean flag=true;
public synchronized void sub(){
while(!flag){// 用while防止假唤醒
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread:"+j);
}
flag=false;
this.notify();
}
public synchronized void main(){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread:"+j);
}
flag=true;
this.notify();
}
}
public class SynTest {
public static void main(String[] args) {
final Business b=new Business();
new Thread(
new Runnable(){
@Override
public void run() {
for(int i=1;i<=50;i++){
b.sub();
}
}
}).start();
new Thread(
new Runnable(){
@Override
public void run() {
for(int i=1;i<=50;i++){
b.main();
}
}
}).start();
}
}
class Business {
private boolean flag=true;
public synchronized void sub(){
while(!flag){// 用while防止假唤醒
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread:"+j);
}
flag=false;
this.notify();
}
public synchronized void main(){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread:"+j);
}
flag=true;
this.notify();
}
}