这次没有使用 有名内部类 将程序控制数据、执行程序都独立出来了
5条线程按照给定规律轮流打印 线程调度 线程池 synchronized wait notify
代码如下:
1.独立出来的内部控制数据类
package com.lovo.homework02;
/**
* 类:将内部数据独立出来 方便修改和控制
* @author Abe
*
*/
public class PrintThreadContext {
/**
* 允许执行的线程的key 初始值为3 (第4条线程)
*/
public static int allowedKey = 3;
/**
* 方法:转换到下一个允许执行线程的key
* 这里是 下次执行本线程后的第二条线程,超出范围时,又从第一条线程开始数
*/
public static void next(){
PrintThreadContext.allowedKey += 2;
if (PrintThreadContext.allowedKey > 4) {
PrintThreadContext.allowedKey %= 5;
}
}
/**
* 循环运行次数
*/
public static int number = 100;
}
2.线程的主程序
package com.lovo.homework02;
/**
* 类:打印线程,按照PrintThreadContext.next()的规律打印
* @author Abe
*/
public class PrintThread implements Runnable {
private String str;
private int key;
private static Object obj = new Object();
public PrintThread(String str, int key) {
this.str = str;
this.key = key;
}
@Override
public void run() {
for (int i = 0; i < PrintThreadContext.number; i++) {
//这里还是加上了程序锁 而不是用while循环代替 是因为 随着线程的增多 每次只有一条线程能进入执行
//其余的都在while里无限循环 我的机器就瞬间卡爆了…… 直到执行完才能动……
synchronized (obj) {
while (key != PrintThreadContext.allowedKey) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(str);
//调用方法:next()
PrintThreadContext.next();
obj.notifyAll();
}
}
}
}
3.执行程序
package com.lovo.homework02;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 类:打印线程的执行程序,
* @author Abe
*
*/
public class PrintThreadRunner {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
String[] strs = { "A", "B", "C", "D", "E" };
for (int i = 0; i < 5; i++) {
service.execute(new PrintThread(strs[i], i));
}
service.shutdown(); //记住关闭线程池
}
}