本帖最后由 zf2501 于 2016-11-21 20:18 编辑
package copackage com.heima.lianxi;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Demo43 {
/*
* 项目下有个xxx.txt文件,里面存了十个小朋友的名字,开始两个线程,每隔两秒执行一次,十个小朋友去打疫苗
* 窗口A和窗口B交替执行,打印结果为小明在窗口A打疫苗
*/
public static void main(String[] args) {
final Vaccinum v = new Vaccinum();
new Thread("窗口A") {
public void run() {
try {
v.vac1();
} catch (Exception e) {
}
}
}.start();
new Thread("窗口B") {
public void run() {
try {
v.vac2();
} catch (Exception e) {
}
}
}.start();
}
}
class Vaccinum {
private static int num = 0;
private int falt = 1;
public void vac1() throws Exception {
ArrayList<String> list = getList();
while(num < 10){
synchronized (this) {
if (falt != 1) {
this.wait();
}
Thread.sleep(2000);
System.out.println(list.get(num) + "在"
+ Thread.currentThread().getName() + "打了疫苗");
num++;
falt = 2;
this.notify();
}
}
}
public void vac2() throws Exception {
ArrayList<String> list = getList();
while(num < 10){
synchronized (this) {
if (falt != 2) {
this.wait();
}
Thread.sleep(2000);
System.out.println(list.get(num) + "在"
+ Thread.currentThread().getName() + "打了疫苗");
num++;
falt = 1;
this.notify();
}
}
}
private ArrayList<String> getList() throws FileNotFoundException,
IOException {
BufferedReader br = new BufferedReader(new FileReader("times.txt"));
ArrayList<String> list = new ArrayList<>();
String name;
while ((name = br.readLine()) != null) {
list.add(name);
}
return list;
}
}
//不知道能不能帮上你... |