package Thread;
/**
public class ThreadAltermate {
public static void main(String[] args) {
final Business business = new Business();
new Thread(){
public void run() {
for(int i=0; i<50; i++){
business.son();
}
}
}.start();
for(int i=0; i<50; i++){
business.parent();
}
}
}
/**
* 1、synchronized在这里的锁是Business对象,作用:parent和son函数互斥
* 2、flag和wait,作用是:让parent和son完成各自函数内的代码再切换运行
*/
class Business{
boolean flag = true;
public synchronized void parent(){
while(flag){
try {
System.out.println("-----parent wait----");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0; i<10; i++){
System.out.println("-----parent run----" + i);
}
flag = true;
this.notify();
}
public synchronized void son(){
while(!flag){
try {
System.out.println("-----son wait----");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0; i<100; i++){
System.out.println("-----son run----" + i);
}
flag = false;
this.notify();
}
}
/**
* 实现效果:主线程运行10次,子线程运行100次,主线程和子线程循环交替运行50次
主要演示synchronized和wait、notify的使用
* 适用场景:只有两个线程的情况,呵呵
*/public class ThreadAltermate {
public static void main(String[] args) {
final Business business = new Business();
new Thread(){
public void run() {
for(int i=0; i<50; i++){
business.son();
}
}
}.start();
for(int i=0; i<50; i++){
business.parent();
}
}
}
/**
* 1、synchronized在这里的锁是Business对象,作用:parent和son函数互斥
* 2、flag和wait,作用是:让parent和son完成各自函数内的代码再切换运行
*/
class Business{
boolean flag = true;
public synchronized void parent(){
while(flag){
try {
System.out.println("-----parent wait----");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0; i<10; i++){
System.out.println("-----parent run----" + i);
}
flag = true;
this.notify();
}
public synchronized void son(){
while(!flag){
try {
System.out.println("-----son wait----");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i=0; i<100; i++){
System.out.println("-----son run----" + i);
}
flag = false;
this.notify();
}
}