多线程设计模式 -- balking
2009-09-17 00:00:00 来源:WEB开发网//操作数据
Java代码
public class Data {
private String filename; //修改是的名字
private String content; // 资料的内容
private boolean changed; //修改后的内容还没存储的话,值为true
public Data(String filename, String content) {
this.filename = filename;
this.content = content;
this.changed = true;
}
// 修改资料内容
public synchronized void change(String newContent) {
content = newContent;
changed = true;
}
// 若有资料修改,就存储到挡安里
public synchronized void save() throws IOException {
//如果内容没有改变就返回
if (!changed) {
System.out.println(Thread.currentThread().getName() + " balks");
return;
}
doSave();
changed = false;
}
// 实际资料储存到挡案里用的方法
private void doSave() throws IOException {
System.out.println(Thread.currentThread().getName() + " calls doSave, content = " + content);
Writer writer = new FileWriter(filename);
writer.write(content);
writer.close();
}
}
保存线程
Java代码
public class SaverThread extends Thread {
private Data data;
public SaverThread(String name, Data data) {
super(name);
this.data = data;
}
public void run() {
try {
while (true) {
//每1秒保存一次
data.save(); // 存储资料
Thread.sleep(1000); // 休息约1秒
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
改变线程
Java代码
public class ChangerThread extends Thread {
private Data data;
private Random random = new Random();
public ChangerThread(String name, Data data) {
super(name);
this.data = data;
}
public void run() {
try {
for (int i = 0; true; i++) {
data.change("No." + i); //修改资料
Thread.sleep(random.nextInt(1000)); // 模拟去做别的事情
data.save(); // 明确的要求存档
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试线程
Java代码
public class Main {
public static void main(String[] args) {
Data data = new Data("data.txt", "(empty)");
new ChangerThread("ChangerThread", data).start();
new SaverThread("SaverThread", data).start();
}
}
适用性
1.不需要刻意去执行的时候
2.不想等待警戒条件成立时
更多精彩
赞助商链接