import java.io.PrintWriter;
import java.util.Scanner;
public class Zuoye8 {
public static void main(String[] args) {
//创建容器
Ram ram = new Ram();
//生产者
Console console = new Console(ram);
//消费者
MyFile myFile = new MyFile(ram);
console.start();
myFile.start();
}
}
/**容器(内存)*/
class Ram{
/**从控制器读取到的数据*/
private String content;
/**判断容器是否已满*/
private boolean isFull;
/**控制器输入流*/
private Scanner sc;
/**向文件中写出数据*/
private PrintWriter out;
public Ram() {
try {
sc = new Scanner(System.in);
out = new PrintWriter("D:/线程.txt","utf-8");
} catch (Exception e) {
e.printStackTrace();
}
}
/**从控制器读取数据的方法
* @throws InterruptedException */
public synchronized void readData() throws InterruptedException {
//1、先判断容器是否已满
if(isFull) {
this.wait();
}
//2、从控制台读取数据
System.out.println("请输入内容:");
content = sc.nextLine();
//3、修改标志位
isFull = true;
//4、通知其他线程
this.notify();
}
/**将内容写出到文件
* @throws InterruptedException */
public synchronized void writeData() throws InterruptedException {
//1、判断容器是否已满
if(!isFull) {
this.wait();
}
//2、写出数据到文件
out.println(content);
out.flush();
//3、修改标志位
isFull = false;
//4、通知其他线程
this.notify();
}
}
/**生产者(控制台)*/
class Console extends Thread{
private Ram ram;
public Console(Ram ram) {
this.ram = ram;
}
@Override
public void run() {
while(true) {
try {
ram.readData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**消费者(文件)*/
class MyFile extends Thread{
private Ram ram;
public MyFile(Ram ram) {
this.ram = ram;
}
@Override
public void run() {
while(true) {
try {
ram.writeData();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
07-28
798