Thread类
继承Thread类需要重写run线程体, idea快捷键Ctrl + O,选择run();
此时,实现类拥有父类方法start,使用子类对象调用start即可启动线程,
缺点,直接继承Thread方式,只能执行绑定的run方法任务,不灵活,不推荐此方式。
public class TestThread1 extends Thread {
// 重写线程体
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程执行--"+i);
}
}
public static void main(String[] args) {
// 开启子线程
TestThread1 t1 = new TestThread1();
t1.start();
for (int i = 0; i < 20; i++) {
System.out.println("主线程执行--" +i);
}
}
}
Runnable接口
实现Runnable接口,重写run线程体,
此时子类只有Runnable的方法,所以需要建立一个Thread对象来开启线程。
此方式只用定义线程体,后续将次任务分配给线程对象即可;
灵活 ,推荐使用;
public class TestThread3 implements Runnable{
// 重写线程体
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("子线程执行--"+i);
}
}
public static void main(String[] args) {
// 开启子线程
TestThread3 t3 = new TestThread3();
new Thread(t3).start();
for (int i = 0; i < 20; i++) {
System.out.println("主线程执行--" +i);
}
}
}
Callable接口
可以定义返回值,
可以拦截异常。
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
// Callable方式异步下载图片
public class TestCallable implements Callable {
//定义变量
private String url;
private String name;
// 构造器注入变量
public TestCallable(String url,String name){
this.url = url;
this.name = name;
}
// 定义下载任务
@Override
public Object call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件:"+name);
return "re_obj";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 构造器赋值
TestCallable t1 = new TestCallable("http://pic.netbian.com/uploads/allimg/201005/232949-1601911789a69f.jpg","1.jpg");
TestCallable t2 = new TestCallable("http://pic.netbian.com/uploads/allimg/201005/232949-1601911789a69f.jpg","2.jpg");
TestCallable t3 = new TestCallable("http://pic.netbian.com/uploads/allimg/201005/232949-1601911789a69f.jpg","3.jpg");
/// A、直接线程启动
FutureTask task1 = new FutureTask<>(t1);
FutureTask task2 = new FutureTask<>(t2);
FutureTask task3 = new FutureTask<>(t3);
new Thread(task1).start();
new Thread(task2).start();
new Thread(task3).start();
/// B、线程池启动
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 提交执行
Future r1 = executorService.submit(t1);
Future r2 = executorService.submit(t2);
Future r3 = executorService.submit(t3);
// 测试submit返回值
System.out.println(r1.get()+"\t"+r2.get()+"\t"+r3.get());
// 关闭线程池
executorService.shutdown();
}
}
/** 定义下载器
未定义位置则下载在项目路下
*/
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异常,downloader方法异常!");
}
}
}
//
下载了文件:2.jpg
下载了文件:1.jpg
下载了文件:3.jpg
re_obj re_obj re_obj