背景
Java多线程的创建方式。
实现
方式一:继承Thread类
注:
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不推荐使用,避免出现OOP单继承局限性
代码
package com.langjialing;
public class ThreadDemo0 extends Thread{
//重写Thread的run()方法
@Override
public void run(){
for (int i = 0; i < 2000; i++) {
System.out.println("多线程……" + i);
}
}
public static void main(String[] args) {
//创建线程对象
ThreadDemo0 t1 = new ThreadDemo0();
//调用start()方法开启线程
t1.start();
//main线程
for (int i = 0; i < 5000; i++) {
System.out.println("主函数" + i);
}
}
}
效果
方式二:实现Runnable接口(推荐)
注:
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用,避免了单继承局限性,同一个对象可以被多个线程使用
代码
package com.langjialing;
public class ThreadDemo1 implements Runnable{
@Override
public void run(){
for (int i = 0; i < 1000; i++) {
System.out.println("多线程……"+ i );
}
}
public static void main(String[] args) {
//创建Runnable接口的实现类对象
ThreadDemo1 t1 = new ThreadDemo1();
//创建线程对象,通过线程对象来开启多线程
Thread thread = new Thread(t1);
thread.start();
// new Thread(t1).start(); //上面两行代码也可简化为此行代码
for (int i = 0; i < 5000; i++) {
System.out.println("主函数……" + i);
}
}
}
效果
方式三:实现Callable接口
代码
package com.langjialing;
import java.util.concurrent.*;
public class ThreadDemo2 implements Callable<Boolean> {
private String no;
//使用构造方法传入参数
public ThreadDemo2(String no){
this.no = no;
}
@Override
public Boolean call(){
for (int i = 0; i < 2000; i++) {
System.out.println("多线程"+no+"……" + i);
}
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadDemo2 t1 = new ThreadDemo2("1");
ThreadDemo2 t2 = new ThreadDemo2("2");
ThreadDemo2 t3 = new ThreadDemo2("3");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
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.shutdown();
}
}
效果
总结
多线程有三种方式来创建:
- 继承Thread类;
- 实现Runnable接口(推荐);
- 实现Callable接口。