java入坑系列7-java多线程三种方式学习笔记
java入坑系列7-java多线程三种方式学习笔记
你好! 这是关于java多线程的学习笔记。总结了3个方式实现java多线程。下面就详细总结一下。
继承Thread类
实现步骤:
- 定义类并继承Thread
- 实现
run()
方法 - 通过
start()
方法启动线程
例子代码:
public class TestThread extends Thread {
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("run 线程:" + i);
}
}
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.start();
for (int i = 0; i < 2000; i++) {
System.out.println("主进程:" + i);
}
}
}
运行结果:
主进程:46
主进程:47
主进程:48
主进程:49
主进程:50
主进程:51
run 线程:0
run 线程:1
run 线程:2
run 线程:3
run 线程:4
run 线程:5
run 线程:6
run 线程:7
run 线程:8
实现Runnable接口(推荐使用此方法)
实现步骤
- 定义类并实现
Runnable
接口 - 实现
run()
方法,编写线程执行体 - 创建线程对象,调用
start()
方法启动线程
public class TestThread3 implements Runnable {
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("run 线程:" + i);
}
}
public static void main(String[] args) {
TestThread3 testThread3 = new TestThread3();
new Thread(testThread3).start();
for (int i = 0; i < 2000; i++) {
System.out.println("主进程:" + i);
}
}
}
实现Callable接口
- 实现
Callable
接口,需要返回值类型 - 重写
call
方法,需要抛出异常 - 创建目标对象
- 创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(1)
; - 提交执行:
Future<Boolean> result1 = ser.submit(t1);
- 获取结果:
boolean r1 = result1.get();
- 关闭服务:
ser.shutdownNow();
public class TestCallable extends Callable {
private String url;
private String name;
public TestCallable (String url,String name){
this.url = url;
this.name = name;
}
public Boolean call(){
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载的文件名:" + name);
return true;
}
public static void main(String[] args) {
TestCallable t1 = new TestCallable ("https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB18nvUz.img?h=174&w=300&m=6&q=60&u=t&o=t&l=f&f=jpg"
,"1.jpg");
TestCallable t2= new TestCallable ("https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB196zoa.img?h=174&w=300&m=6&q=60&u=t&o=t&l=f&f=jpg"
,"2.jpg");
TestCallable t3 = new TestCallable ("https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1bO89F.img?h=174&w=300&m=6&q=60&u=t&o=t&l=f&f=jpg"
,"3.jpg");
ExecutorService ser = Executors.newFixedThreadPool(1);
Future<Boolean> r1= ser.submit(t1);
Future<Boolean> r2= ser.submit(t2);
Future<Boolean> r3= ser.submit(t3);
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
ser.shutdownNow();
}
}
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");
}
}
}