三种创建方法
- Thread class: 继承Thread类
- Runable 接口: 实现Runable接口
- Callable 接口: 进阶方法
方法一:
public class Thread1 extends Thread{
@Override
public void run() {
for(int i = 0;i<20;i++){
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args){
//main线程,主线程
Thread1 thread1 = new Thread1();
thread1.start();
for(int i = 0;i<20;i++){
System.out.println("我在学习多线程---"+i);
}
}
}
注意调用时要调用thread1.start()方法而不是run方法,这个方法我们要对其经行重写。
普通方法和多线程方法
实现一个网图的下载
package ThreadTest;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Thread2 extends Thread{
private String url;
private String name;
public Thread2(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("down img "+ name);
}
public static void main(String[] args) {
Thread2 thread2 = new Thread2("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5","1.jpg");
Thread2 thread3 = new Thread2("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5","2.jpg");
Thread2 thread4 = new Thread2("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5","3.jpg");
thread2.start();
thread3.start();
thread4.start();
}
}
class WebDownLoader{
//download methods
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 Exception: cannot down file from "+ url);
}
}
}
方法二:实现Runable接口(推荐)
与方法一相似:
public class Thread3 implements Runnable{
@Override
public void run() {
for(int i = 0;i<20;i++){
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args){
//main线程,主线程
//creat a thread, through implement Runnable
Thread3 thread3 = new Thread3();
//creat a thread, through implement Runnable
Thread thread = new Thread(thread3);
thread.start();
for(int i = 0;i<20;i++){
System.out.println("我在学习多线程---"+i);
}
}
}
两种方法的对比
举个例子
同时使用一个继承了Run able的类,开始线程
public class Thread4 implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while(true){
if(ticketNums<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"拿到了第:"+"-->"+ticketNums--+"票");
}
}
public static void main(String[] args){
Thread4 thread4 = new Thread4();
new Thread(thread4,"小明").start();
new Thread(thread4,"老师").start();
new Thread(thread4,"黄牛").start();
}
}
方法三:Callable接口(进阶用法)
Callable创建步骤
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFiexedThreadPool(1)
- 提交执行:Future<Boolean> result1 = ser.submit(t1)
- 获取结果:boolean r1 = result1.get()
- 关闭服务:ser.shutdownNow();
实现:以服务的方式来执行和管理线程
package CallableTest;
import ThreadTest.Thread2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//thread create 3, implement Callable interface
/*
callable value
1. call() can have return value
2. call() can throw exception
3. Callable is support generics
*/
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url, name);
System.out.println("down img " + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable thread2 = new TestCallable("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5", "1.jpg");
TestCallable thread3 = new TestCallable("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5", "2.jpg");
TestCallable thread4 = new TestCallable("https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&lid=11518414591934254436&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined©right=undefined&cs=643099680,3981932767&os=3881055764,3039537278&simid=3370890584,454352292&pn=0&rn=1&di=7482437761027276801&ln=513&fr=&fmq=1744548171969_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=1e&objurl=https%3A%2F%2Fb0.bdstatic.com%2Fugc%2FzmllNPEiGh2DP0n_rbvV2wced35015a76fb7f0cd38f5e3ae8a97ed.jpg%3Fx-bce-process%3Dimage%2Fauto-orient%2Co_1%2Fwatermark%2Cimage_NDU0ZjAyZDU5YjQ1LnBuZw%3D%3D%2Cbucket_searchbox%2Cw_38%2Ctext_QOiIrOiLpeazoue9l-Wvhm15%2Ctype_RlpMYW5UaW5nSGVp%2Csize_38%2Cx_26%2Cy_26%2Cinterval_4%2Ccolor_FFFFFF%2Ceffect_softoutline%2Cshc_000000%2Cblr_2%2Calign_1%40h_1280&rpstart=0&rpnum=0&adpicid=0&nojc=undefined&dyTabStr=MCwxMiwzLDEsMiwxMyw3LDYsNSw5", "3.jpg");
//creat execute service
ExecutorService executeService = Executors.newFixedThreadPool(3);
//submit execute
Future<Boolean> r1 = executeService.submit(thread2);
Future<Boolean> r2 = executeService.submit(thread3);
Future<Boolean> r3 = executeService.submit(thread4);
//get result
Boolean rs1 = r1.get();
Boolean rs2 = r2.get();
Boolean rs3 = r3.get();
System.out.println("线程1结果:"+rs1);
System.out.println("线程1结果:"+rs2);
System.out.println("线程1结果:"+rs3);
//close
executeService.shutdown();
}
}
class WebDownLoader {
//download methods
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 Exception: cannot down file from " + url);
}
}
}