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 11:06:50 浏览: 185
多线程传输文件(可以运行)
代码如下:
```
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((long) (3000 + Math.random() * 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((long) (3000 + Math.random() * 3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("File: " + fileName + " has been sent.");
}
}
public class TestThread {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 5; i++) {
threads[i] = new Thread(new ReceiveFileRunnable("file" + (i + 1) + ".txt"));
threads[i + 5] = new Thread(new SendFileRunnable("file" + (i + 1) + ".txt"));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("QQ文件收发任务结束");
}
}
```
解释:
1. ReceiveFileRunnable类和SendFileRunnable类分别实现了Runnable接口,并在run()方法中完成了题目要求的功能。
2. TestThread类中,我们先创建了10个线程,其中前5个为ReceiveFileRunnable线程,后5个为SendFileRunnable线程。
3. 在启动所有线程之后,我们使用join()方法等待所有线程执行完毕。
4. 最后打印"QQ文件收发任务结束"。
阅读全文