一、继承Thread类
过程:1.写一个类去继承Thread类 2 .重写run方法 3. 在测试类中创建子类的对象 4 .再用子类对象调用start方法开启线程
1.1 代码示例 创建两个线程去打印10次helloword
MyThread类
/*
* Copyright (c) 2020, 2023, webrx.cn All rights reserved.
*
*/
package huang2;
public class MyThread extends Thread {
@Override
public void run() {
//书写线程要执行的代码 eg:打印100次Hello word
for (int i = 0; i < 10; i++) {
System.out.println(getName() + "hello word");
}
}
}
测试类
package huang2;
public class ThreadDemo {
//1 定义一个类继承Thread类 2 重写run方法 3 创建子类的对象 4 开启线程
public static void main(String[] args) {
//创建子类的对象 并启动线程
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
//给两个线程起个名字
t1.setName("线程一");
t2.setName("线程二");
//开启线程
t1.start();
t2.start();
}
}
1.2 运行结果展示
二、实现Runnable接口
核心步骤 :1. 创建一个类实现Runnable接口 2.重写run方法 3.创建自己类的对象 4.创建一个Thread类的对象 5.将自己类的对象作为参数添加到Thread类中。
2.1 代码示例 打印10次hello word
MyRun类
package huang2;
public class MyRun implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//currentThread方法 先获取当前线程的对象 看看是那个线程在执行这个方法 再返回这个对象
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + "hello word");
}
}
}
测试类
package huang2;
public class ThreadDemo1 {
public static void main(String[] args) {
//1 创建自己类的对象 2 创建Thread类的对象 3 将自己类的对象作为参数传入Thread类中
MyRun m1 = new MyRun();
Thread t1 = new Thread(m1);
Thread t2 = new Thread(m1);
t1.setName("线程一");
t2.setName("线程二");
t1.start();
t2.start();
}
}
2.2 运行结果展示
三、实现Callable接口
特点:可以获取到多线程运行的结果
步骤:1 .创建一个类实现Callable接口 2 .重写call方法(有返回值 表示多线程运行的结果)
3.创建子类的对象(表示多线程运行的结果)4创建FutureTask的对象(作用:管理多线程运 行的结果) 5.创建Thread类的对象并启动start方法
3.1 代码示例(求1-100的和)
ThreadDemo3类
package huang2;
import java.util.concurrent.Callable;
public class ThreadDemo3 implements Callable<Integer> {//泛型表示结果的类型
@Override
public Integer call() throws Exception {
//1-100和
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
}
测试类
package huang2;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Text {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建子类的对象(表示多线程要执行的任务)
ThreadDemo3 mc = new ThreadDemo3();
//创建FutureTask对象(管理多线程运行的结果)
FutureTask<Integer> ft = new FutureTask<>(mc);
//创建Thread的对象 开启线程(创建线程)
Thread t1 = new Thread(ft);
//开启线程
t1.start();
//获取多线程运行的结果
Integer result = ft.get();
System.out.println(result);
}
}
3.2 运行结果展示