一、继承Thread类
public class TestThread1 extends Thread {
//副线程
public void run(){
for (int i = 0; i <20 ; i++) {
System.out.println("我在学习java");
}
}
//main,主线程
public static void main(String[] args) {
//副线程启动
TestThread1 testThread1 = new TestThread1();
testThread1.start();
for (int i = 0; i <20 ; i++) {
System.out.println("我在吃饭");
}
}
}
二、实现Runnable接口
public class TestThread3 implements Runnable {
//副线程
public void run(){
for (int i = 0; i <20 ; i++) {
System.out.println("我在学习java");
}
}
//main,主线程
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启线程,代理
//Thread thread = new Thread(testThread3);
//thread.start();
new Thread(testThread3).start();
for (int i = 0; i <100 ; i++) {
System.out.println("我在吃饭");
}
}
}
三、实现Callable接口
//线程创建方式三:实现callable接口
//优点:可以定义返回值类型,可以抛出异常
public class TestCallable implements Callable {
private String url;//网络图片地址
private String filename;//保存的文件名
public TestCallable(String url,String filename){
this.url = url;
this.filename = filename;
}
//下载图片线程的执行体
public Boolean call() {
WebDownLoad webDownLoad = new WebDownLoad();
webDownLoad.downloader(url,filename);
System.out.println("下载了文件名为:"+filename);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://pics2.baidu.com/feed/32fa828ba61ea8d34c7cb6cb530c7644241f58b0.png?token=ae95ec0bbcf9d978e434c0ff1ae984ea","a1.jpg");
TestCallable t2 = new TestCallable("https://pics5.baidu.com/feed/314e251f95cad1c8512f7444bf382103c83d51ca.jpeg?token=2285fba0b9ca8603690be82ae1b95bba","a2.jpg");
TestCallable t3 = new TestCallable("https://pics5.baidu.com/feed/91529822720e0cf36459feecc840b415be09aa08.jpeg?token=7b41f4d8465de0909a6eb82180ced050","a3.jpg");
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
//提交执行,相当于start()
Future r1 = executorService.submit(t1);
Future r2 = executorService.submit(t2);
Future r3 = executorService.submit(t3);
//获取结果
Boolean rs1 = r1.get();
Boolean rs2 = r2.get();
Boolean rs3 = r3.get();
System.out.println(rs1.toString()+rs2+rs3);
//关闭服务
executorService.shutdownNow();
}
}
//下载器
class WebDownLoad{
//下载方法
public void downloader(String url,String filename) {
try {
FileUtils.copyURLToFile(new URL(url),new File(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
}