继承Thread类
public class TestThread extends Thread{
private String url;
private String name;
public TestThread(String url,String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloadPic webDownloadPic = new WebDownloadPic();
webDownloadPic.downLoadPic(url,name);
}
public static void main(String[] args) throws InterruptedException {
TestThread thread1 = new TestThread("http://192.168.11.140:8085/pictures/picOne.png","1.jpg");
TestThread thread2 = new TestThread("http://192.168.11.140:8085/pictures/picTwo.png","2.jpg");
TestThread thread3 = new TestThread("http://192.168.11.140:8085/pictures/picOne.png","3.jpg");
thread2.start();
thread2.join();
thread1.start();
thread1.join();
thread3.start();
}
}
class WebDownloadPic{
// 下载方法
public void downLoadPic(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
System.out.println(Thread.currentThread().getName() + ":下载图片:" + name);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实现Runnable接口
与Thread的区别就是:实现Runnable接口可以一个对象跑多线程
public class TestRunable implements Runnable{
private String name;
public TestRunable(String name){
this.name = name;
}
@Override
public void run() {
Test test = new Test();
test.print(name);
}
public static void main(String[] args) {
// ABC为线程名称
TestRunable t1 = new TestRunable("A");
TestRunable t2 = new TestRunable("B");
TestRunable t3 = new TestRunable("C");
// new Thread(t1,"A").start();
new Thread(t1).start();
new Thread(t3).start();
new Thread(t2).start();
}
}
class Test{
public void print(String name){
for(int i = 0 ; i < 100 ; i ++){
System.out.println(Thread.currentThread().getName() + "打印了:" + name);
}
}
}
实现Callable接口
实现call()方法,别的不去了解