编写程序实现如下功能:一个线程进行如下运算 1*2+2*3+3*4+…+19*20,而另一个线程每隔一段时间读取前一个线程的运算结果。

线程间交互同步

在进行多线程程序设计时,会遇到如何控制相互交互的线程之间的运行进度,即线程间交互同步。典型的模型是“生产者——消费者”问题。

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();
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值