线程间交互同步
在进行多线程程序设计时,会遇到如何控制相互交互的线程之间的运行进度,即线程间交互同步。典型的模型是“生产者——消费者”问题。
public class ShareData {
private int sum;
private boolean CountingFlag = false;
public synchronized void putShareSum(int sum) {
if(CountingFlag == true)
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
this.sum = sum;
CountingFlag = true;
notify();
}
public synchronized int getShareSum() {
if(CountingFlag == false) {
try {
wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
CountingFlag = false;
notify();
return sum;
}
}
class CountingThread implements Runnable{
private String name;
ShareData s;
private int i;
private static int j = 2;
static int sum = 0;
public CountingThread(String name, ShareData s){
this.name = name;
this.s = s;
}
@Override
public void run() {
// TODO 自动生成的方法存根
System.out.println("线程启动:" + this.name);
for(i = 1; i <= 19; i++) {
sum += (i * j);
s.putShareSum(sum);
j++;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
public static int getJ() {
return j;
}
}
class OutputThread implements Runnable{
private ShareData s;
private String name;
public OutputThread (String name,ShareData s) {
this.name = name;
this.s = s;
}
@Override
public void run() {
int sum;
do {
sum = s.getShareSum();
System.out.println("当前计算结果为" + sum);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}while(CountingThread.getJ() != 21);
}
}
public class ProcessDemo {
public static void main(String args[]) {
ShareData s = new ShareData();
CountingThread ct = new CountingThread("计算线程", s);
OutputThread ot = new OutputThread("输出线程", s);
Thread c = new Thread(ct);
Thread o = new Thread(ot);
c.start();
o.start();
}
}