一、实验项目要求
实验目的
- 熟练掌握线程的概念和线程的状态;
- 熟练掌握通过Thread类的子类实现多线程的方法;
- 熟练掌握通过实现Runnable接口实现多线程的方法。
- 熟悉按不同的方式I/O输入输出流的分类。
- 熟悉字节类I/O流、字符类I/O流的使用
- 熟悉文件操作和文件I/O。
实验内容
1.用多线程实现生产者—消费者问题。
2.编写一个HelloWorld.java,选择合适的输入输出流将源程序文件复制一份到“Test.txt”文件中、并同时将文件的内容打印到控制台窗口中。
二、实验环境
Ecplise
三、理论分析或算法分析
问题一实验步骤
1.复习有关多线程的相关内容;
2.根据界面要求,分析需要用到的布局管理器及组件;
3.根据功能要求,分析文字移动的控制逻辑;
4.根据上述分析结果编写代码;
5.调试代码,完善程序
问题二实验步骤
- 复习输入输出流相关内容;
- 分析题目要求,选择合适的输入输出流;
- 按要求编写程序;
- 分析实验结果。
- [实验报告要求]
- 阐述实验目的和实验内容;
- 分析程序的执行过程;
- 给出程序的最终实现结果。
四、实现方法
问题1
package worker;
/**
* 一个生产者--消费者,且共享区间的容量为1
* @author 24487
* May 19, 2021
*/
//共享数据区,同步方法
class HoldInt {
int sharedInt; //共享数据
private boolean writeAble = true; //标记变量,是否可以存
//生产数据
public synchronized void produce(int val)
{
while (writeAble==false) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sharedInt = val;
System.out.println("生产者 "+Thread.currentThread().getName() +";生产数据:"+ sharedInt);
writeAble = false;
notify();
}
//消费数据
public synchronized void consume()
{
while (writeAble==true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者 " + Thread.currentThread().getName()+";消费数据:"+sharedInt );
writeAble = true;
notify();
}
}
//生产者
class ProduceInt implements Runnable {
private HoldInt hi;
public ProduceInt(HoldInt hiForm) {
hi = hiForm;
}
public void run() {
for (int i = 1; i <= 4; i++) {
hi.produce(i);
}
}
}
//消费者
class ConsumeInt implements Runnable {
private HoldInt hi;
public ConsumeInt(HoldInt hiForm) {
hi = hiForm;
}
public void run() {
for (int i = 1; i <= 4; i++) {
hi.consume();
}
}
}
public class Produce_ConsumTest {
public static void main(String[] args) {
HoldInt h = new HoldInt();
// 生产者
Thread pThread=new Thread(new ProduceInt(h));
// 消费者
Thread cThread=new Thread(new ConsumeInt(h));
pThread.start();
cThread.start();
}
}
问题2
package task;
import java.io.FileWriter;
import java.io.IOException;
public class HelloWorld {
public static void main(String[] args) throws IOException {
//创建一个FileWriter对象用于向文件中写入数据
FileWriter writer =new FileWriter("Test.txt");
String str="HelloWorld!";
writer.write(str);
System.out.println(str);
writer.write("\r\n");
writer.close();
}
}
五、实验结果分析
问题1结果
问题2结果
所遇问题以及处理方法
1.第一个代码是在复制的老师的,所有有所不理解,但是多看看尽力去理解吧;
2.在码代码的过程中,经常会出现红线报错,一个一个搜索去解决,不要太着急,否则什么也做不出来,要多看代码,进行长时间的练习,这样就可以熟悉了;
3.多看书,多码代码,增加自己的熟练程度;
4.多进行实践训练,可以增加自己对知识的熟悉,每次敲一次代码都会有一次新的收获。