[再新]创建子父线程,子线程优先执行3次,父线程执行5次,如此循环10次
基于上一次的一个文件两个类的基础上,继续简洁代码,实现一个文件一个类,两条线程。
/**
* @author
* 一个类上实现父子线程循环交替
* 这个类直接继承Thread类
*/
public class NewFAndS extends Thread{
/**
* 重写run方法
*/
public void run(){
this.setName("子-线-程");
for(int i = 0;i < 10; i++){
son(i);
}
}
//定义一个控制开关
private Boolean flag = true;
/**
* @param args
* 程序入口
*/
public static void main(String[] args) {
//本类的实例化对象
final NewFAndS n = new NewFAndS();
//创建子线程并运行
n.start();
//主线程运行
for(int i = 0;i < 10; i++){
Thread.currentThread().setName("父-线-程");
n.father(i);
}
}
/**
* 父线程调用的方法
* @param j
*/
public synchronized void father(int j){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0;i < 3; i++){
System.out.println("线程"+Thread.currentThread().getName()+"执行第"+(i+1)+"次,第"+(j+1)+"次循环");
}
flag = true;
this.notify();
}
/**
* 子线程调用的方法
* @param j
*/
public synchronized void son(int j){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0;i < 5; i++){
System.out.println("线程"+Thread.currentThread().getName()+"执行第"+(i+1)+"次,第"+(j+1)+"次循环");
}
flag = false;
this.notify();
}
}