实现Runnab接口
Posted itzyz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现Runnab接口相关的知识,希望对你有一定的参考价值。
Runnable
package duoxiancheng;
public class Thread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("线程执行");
}
}
public static void main(String[] args) {
//创建runnable接口的实例对象
Thread2 thread2 =new Thread2();
//创建线程对象,通过线程对象开启线程,代理
Thread thread = new Thread(thread2);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("主线程");
}
}
}
多线程下载
package duoxiancheng;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Thread2 implements Runnable{
String url;
String name;
public Thread2(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run() {
Downnn downnn=new Downnn();
downnn.dodd(url,name);
System.out.println("下载了:"+name);
}
public static void main(String[] args) {
Thread2 thread1 = new Thread2("https://n.sinaimg.cn/fashion/590/w240h350/20200618/5242-ivffpcs0137589.jpg","1.jpg");
Thread2 thread2 = new Thread2("https://n.sinaimg.cn/fashion/590/w240h350/20200618/5242-ivffpcs0137589.jpg","2.jpg");
Thread2 thread3 = new Thread2("https://n.sinaimg.cn/fashion/590/w240h350/20200618/5242-ivffpcs0137589.jpg","3.jpg");
new Thread(thread1).start();
new Thread(thread2).start();
new Thread(thread3).start();
}
class Downnn{
public void dodd(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是关于实现Runnab接口的主要内容,如果未能解决你的问题,请参考以下文章