一、1. 用多线程代码来模拟,迅雷用3个线程下载100M资源的的过程。
每个线程每次下载1兆(M)资源,直到下载完毕,即剩余的待下载资源大小为0, (用一个整数表示资源大小, 剩余待下载资源就减少多少兆(M),考虑多线程的数据安全问题)
package com.homework.homework0803;
/**
* @Author jinman1012@qq.com 2020/8/3 19:07
* @Version 1.0
*/
public class Problem1 {
public static void main(String[] args) {
//实例化Runnable子类
MyThread myRunnable = new MyThread();
//实例化线程并启动
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);
Thread thread3 = new Thread(myRunnable);
thread1.start();
thread2.start();
thread3.start();
}
}
class MyThread implements Runnable {
//设置下载总资源大小
int size = 100;
@Override
public void run() {
while(size > 0) {
try {
//假定下载花费时间 单位ms
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
//线程同步代码块
synchronized (this) {
//double check
if(size > 0){
size -= 1;
System.out.println(Thread.currentThread().getName() +
"下载了第" + (100-size) + "M的资源,共剩余" + size + "M");
if(size == 0) System.out.println("下载已完成......");
}
}
}
}
}