Java | PTA练习:生产者和消费者问题

Java | PTA练习:生产者和消费者问题,第1张

Java | PTA练习:生产者消费者问题 题目要求

编写程序,实现生产者和消费者问题。输入:由英文字母和数字组成的不定长度字符串数组,例如{“abc”,”23d”,”1a”}。每隔100毫秒,生产者线程读入数据,放入生产者公用的仓库;消费者从仓库中取出字符串,进行倒置,如上例{“cba”,”d32”,”a1”}; 输出:倒置后的字符串。

提示:可以定义4个类:生产者类、消费者类、产品类和测试类。

代码示例
class Production{
	String [] strings;
	private String aString;
	private Boolean isconsumed=false;
	public Production() {}
	public Production(String [] s) {
		strings = s;
	}
	public synchronized void produce(String s) {
		if(!isconsumed) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		aString = s;
		isconsumed = false;
		notify();
	}
	public synchronized void consume() {
		if(isconsumed) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(aString!=null) {
			for(int i=aString.length()-1;i>=0;i--) {
				System.out.print(aString.charAt(i));
			}
			System.out.println();
		}
		isconsumed=true;
		notify();
	}
}

class Producer implements Runnable{
	private Production production;
	public Producer(Production p) {
		production = p;
	}
	@Override
	public void run() {
		int i=0;
		while(true) {
			try {
				i=i%production.strings.length;
				production.produce(production.strings[i]); 
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			i++;
		}
	}
}
class Consumer implements Runnable{
	private Production production;
	public Consumer(Production p) {
		production = p;
	}
	@Override
	public void run() {
		while(true) {
			production.consume();
		}
	}
}

public class Main {
	public static void main(String[] args) {
		String [] strings={"abc","23d","1a"};
		Production production = new Production(strings);
		new Thread(new Producer(production)).start();
		new Thread(new Consumer(production)).start();
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5522984.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存