多线程
网络原因
进程线程同时进行
//穿插输出
public void run() {
super.run();
for (int i = 0; i < 20; i++) {
System.out.println("ssss"+i);
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
for (int i = 0; i < 300; i++) {
System.out.println("jjjj"+i);
}
}
多线程下载图片
public class TestDownload extends Thread{
private String url;
private String name;
public TestDownload(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) {
TestDownload t1 = new TestDownload("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1091405991,859863778&fm=26&gp=0.jpg","1.jpg");
TestDownload t2 = new TestDownload("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1141259048,554497535&fm=26&gp=0.jpg","2.jpg");
TestDownload t3 = new TestDownload("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3922290090,3177876335&fm=26&gp=0.jpg","3.jpg");
t1.start();
t2.start();
t3.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异常");
}
}
}
Runnable接口
public class TestThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("ssss"+i);
}
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
new Thread(testThread).start();
for (int i = 0; i < 20; i++) {
System.out.println("xxxxxxxx"+i);
}
}
}