实现多线程2----实现Runnable接口
public class TestThread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("学习java"+i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.println("我在睡觉"+i);
}
TestThread3 testThread3 = new TestThread3();
Thread thread=new Thread(testThread3);
thread.start();
}
}
Runnable接口实现多线程同步下载图片
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread4 implements Runnable{
private String url;
private String name;
public TestThread4(String url,String name) {
this.url = url;
this.name=name;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
System.out.println("正在下载的图片为"+name);
}
public static void main(String[] args) {
TestThread4 t1 = new TestThread4("https://img-bss.csdn.net/1596531550646.jpg","3.jpg");
TestThread4 t2=new TestThread4("https://img-bss.csdn.net/1589341773507.jpg","4.jpg");
new Thread(t1).start();
new Thread(t2).start();
}
}
class WebDownLoader{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}