1. 线程的创建与启动 QQ文件传输支持多线程,可以在接收文件的同时进行文件发送。不考虑同一个文件多线程收发的问题,编写ReceiveFileRunnable与SendFileRunnable类(两个类都具有构造方法,带一个String参数,传入收发的文件名),均实现Runnable接口。这两个类的run()方法分别有如下功能: (1)分别打印"I am receiving file:xxx.x" 和"I am sending file:yyy.y",表示开始收发文件;其中,"xxx.x"和"yyy.y"为收发的文件名; (2)休眠3000ms-6000ms间的随机时间(Thread.sleep..);分别打印"File:xxx.x has been received."和"File:yyy.y has been sent.",表示收发结束。 编写TestThread类,在main方法中启动5个ReceiveFileRunnable与5个SendFileRunnable线程。当这5个ReceiveFileRunnable与5个SendFileRunnable线程结束,才执行最后一句代码,打印"QQ文件收发任务结束"(使用join)。
时间: 2023-06-11 21:05:58 浏览: 75
安全文件传输
ReceiveFileRunnable与SendFileRunnable类的实现如下:
```java
public class ReceiveFileRunnable implements Runnable {
private String fileName;
public ReceiveFileRunnable(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
System.out.println("I am receiving file: " + fileName);
try {
Thread.sleep((int)(Math.random()*3000 + 3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("File: " + fileName + " has been received.");
}
}
public class SendFileRunnable implements Runnable {
private String fileName;
public SendFileRunnable(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
System.out.println("I am sending file: " + fileName);
try {
Thread.sleep((int)(Math.random()*3000 + 3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("File: " + fileName + " has been sent.");
}
}
```
TestThread类的实现如下:
```java
public class TestThread {
public static void main(String[] args) throws InterruptedException {
Thread[] receiveThreads = new Thread[5];
Thread[] sendThreads = new Thread[5];
for (int i = 0; i < 5; i++) {
receiveThreads[i] = new Thread(new ReceiveFileRunnable("file" + (i+1) + ".txt"));
sendThreads[i] = new Thread(new SendFileRunnable("file" + (i+1) + ".txt"));
receiveThreads[i].start();
sendThreads[i].start();
}
for (int i = 0; i < 5; i++) {
receiveThreads[i].join();
sendThreads[i].join();
}
System.out.println("QQ文件收发任务结束");
}
}
```
运行结果如下:
```
I am receiving file: file1.txt
I am sending file: file1.txt
I am receiving file: file2.txt
I am sending file: file2.txt
I am receiving file: file3.txt
I am sending file: file3.txt
I am receiving file: file4.txt
I am sending file: file4.txt
I am receiving file: file5.txt
I am sending file: file5.txt
File: file1.txt has been received.
File: file1.txt has been sent.
File: file2.txt has been sent.
File: file2.txt has been received.
File: file5.txt has been sent.
File: file5.txt has been received.
File: file4.txt has been sent.
File: file4.txt has been received.
File: file3.txt has been received.
File: file3.txt has been sent.
QQ文件收发任务结束
```
阅读全文