多线程详解
线程的五大状态和方法
三大不安全案例
死锁
Lock(锁)
线程通信
概念:
线程就是独立的执行路径;
在程序运行时,即时没有自己创建线程,后台也会有多个线程,如主线程,gc线程;
main()称之为主线程,为系统的入口,用于执行整个程序;
在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的。
对同一份资源操作是,会存在资源抢夺的问题,需要加入并发控制;
线程会带来额外的开销,如cpu调度时间,并发控制开销。
每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
线程创建:
三种创建方式:
Thread class----->继承Thread类
Runnable接口----->实现Runnable接口
Callable接口----->是实现Callable接口
1.继承Thread类:
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程(了解)
//继承Thread类
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,,=由CPU调度执行
public class TestThread01 extends Thread{
public void run(){
//run()方法线程体;
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread01 testThread01=new TestThread01();
/**
* start()方法是并替执行
* run()方法是执行完上一个再执行下一个
*/
//调用start()方法开启线程
testThread01.start();
testThread01.run();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
2.实现Runnable接口
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread03 implements Runnable{
@Override
public void run() {
//run()方法线程体;
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread03 testThread03=new TestThread03();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread=new Thread(testThread03);
// thread.start();
/**
* 可以变成一行代码
*/
new Thread(testThread03).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
3.实现Callable接口(了解)
- 实现Callable接口。需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executor.newFixedThreadPool(1) // 1指,运行几个线程
- 提交执行:Future result1 = ser.submit(t1)
- 获取结果:boolean r1 = result1.get()
- 关闭服务:ser.shutdownNow();
总结:
继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
实现Runnable接口
- 实现接口Runnable具备多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
实现Callable接口
- 可以定义返回值
- 可以抛出异常
线程的五大状态和方法
行终止变量,当flag=false,则终止线程运行
//测试stop
//1.建议线程正常停止--->利用次数,不建议死循环
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或者destroy等过时或JDK不建议使用的方法
public class TestStop implements Runnable {
//1.设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("run...Thread" + i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900) {
//调用stop()方法切换标志位,让线程停止
testStop.stop();
System.out.println("该停止了!!!");
}
}
}
}
线程休眠
- 1.sleep(时间)指定当前线程阻塞的毫秒数;
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等;
- 每一个对象都有一个锁,sleep不会释放锁;
//模拟倒计时和现在时间
public class TestSleep02 {
//模拟倒计时
public static void tenDown() throws InterruptedException {
//倒计时10秒
int num = 10;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
/**
* 调用 模拟倒计时 方法
*/
//tenDown();
/**
* 获取当前时间
*/
Date startTime = new Date(System.currentTimeMillis()); //获取当前时间
while (true) {
Thread.sleep(1000); //一秒一次
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); //输出格式
startTime = new Date(System.currentTimeMillis()); //输出完再次获取当前时间(更新时间)
}
}
}
线程礼让(yield)
- 1.礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看cpu心情
//测试礼让线程
//礼让不一定成功,看cpu心情
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield, "a").start();
new Thread(myYield, "b").start();
}
}
class MyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始执行");
Thread.yield(); //礼让
System.out.println(Thread.currentThread().getName() + "线程停止执行");
}
}
Join(插队)
- Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
- 可以想象成插队
//测试join方法
//想象成插队
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程vip来了" + i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if (i == 200) {
thread.join();
}
System.out.println("main" + i);
}
}
}
线程状态观测(Thread.State)线程状态。线程可以处于以下状态之一:
- 1.NEW,尚未启动的线程处于此状态。
- RUNNABLE,在Java虚拟机中执行的线程处于此状态。
- BLOCKED,被阻塞等待监听器锁定的线程处于此状态。
- WAITING,正在等待另一个线程执行特定动作的线程处于此状态。
- TIMED_WAITING,正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
- TERMINATED,已退出的线程处于此状态
一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态
//观察测试线程的状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("//");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state); //NEW
//观察启动后
thread.start(); //启动线程
state = thread.getState();
System.out.println(state); //Run
while (state!=Thread.State.TERMINATED){ //只要线程不停止,就一直输出状态
Thread.sleep(100);
state = thread.getState(); //更新线程状态
System.out.println(state); //输出状态
}
}
}
线程优先级
-
1.Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
-
线程的优先级用数字表示,范围从1~10.
(1). Thread.MIN_PRIORITY=1;
(2). Thread.MAX_PRIORITY=10;
(3). Thread.NORM_PRIORITY=5; -
3.使用以下方式改变或获取优先级-----#.getPriority().setPriority(int xxx)
优先级的设定建议在start()调度前
优先级低只是意味着获取调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度
//测试线程的优先级
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
//设置优先级
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(Thread.MAX_PRIORITY); //Thread.MAX_PRIORITY=10
t3.start();
t4.setPriority(4);
t4.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "======" + Thread.currentThread().getPriority());
}
}
守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如。后台记录操作日志,监控内存,垃圾回收等待…
//测试守护线程
//上帝守护你
/**
* 本身God类会一直执行,但是他变成了守护线程,所以,当You类线程停止,守护线程God也会跟着停止(God会再执行一会,是因为停止需要时间)
*/
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); //默认为false,表示是用户线程,正常的线程都是用户线程... false表示守护线程
thread.start(); //上帝守护线程启动
new Thread(you).start();
}
}
//上帝
class God implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("上帝保佑着你");
}
}
}
//你
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("------goodbye! world!------");
}
}
线程同步
-
由于同一个进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
(1). 一个线程持有锁会导致其他所有需要此锁的线程挂起; (2).在多线程竞争下,加锁,释放锁会导致比较多的上下文切换 和 调度延时,引起性能问题; (3).如果一个优先级高的线程等待一个优先级低的线程释放锁 会导致优先级倒置,引起性能问题。
**三大不安全案例**
第一个
//不安全的买票
//线程不安全,有负数,同票数,0票数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "苦逼的我").start();
new Thread(buyTicket, "牛逼的你们").start();
new Thread(buyTicket, "可恶的黄牛党").start();
}
}
class BuyTicket implements Runnable {
//票
private int ticket = 10;
boolean flag = true; //外部停止方式
@Override
public void run() {
//买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticket <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(1000);
//输出 谁 拿到了第 几 张票
System.out.println(Thread.currentThread().getName() + "拿到第" + ticket-- + "张票");
}
第二个
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "本人");
Drawing girlFriend = new Drawing(account, 100, "静静");
you.start();
girlFriend.start();
}
}
//账户
class Account {
int money; //余额
String name; //卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行
class Drawing extends Thread {
Account account; //账户
int drawingMoney; //取多少钱
int nowMoney; //手里有多少钱
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
public void run() {
//判断卡里的钱,有没有比,取钱的金额,大
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够");
return;
}
//模拟延时a
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡里余额 =卡里钱 - 取的钱
account.money = account.money - drawingMoney;
//手里的钱 = 现在有的钱 + 取的钱
nowMoney = drawingMoney + nowMoney;
System.out.println(account.name + "余额:" + account.money);
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
第三个
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list=new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
**死锁**
多个线程各自占有一些资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“31”时,就可能会发生“死锁”的问题。
死锁案例 和 解决方法:
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup makeup1 = new Makeup(0, "静儿");
Makeup makeup2 = new Makeup(1, "张心怡");
makeup1.start();
makeup2.start();
}
}
//口红
class Lipstick {
}
//镜子
class Mirror {
}
class Makeup extends Thread {
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int chice; //选择
String girlName; //使用化妆品的人
public Makeup(int chice, String girlName) {
this.chice = chice;
this.girlName = girlName;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (chice == 0) {
synchronized (lipstick) { //拿到口红的锁
System.out.println(this.girlName + "拿到了口红的锁");
Thread.sleep(1000);
synchronized (mirror) { //一秒后,拿到镜子的锁
System.out.println(this.girlName + "拿到了镜子的锁");
}
}
} else {
synchronized (mirror) { //拿到镜子的锁
System.out.println(this.girlName+ "拿到了镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) { //一秒后,拿到口红的锁
System.out.println(this.girlName + "拿到了口红的锁");
}
}
}
}
}
/**
* 解决方法,不在同步块中加入同步块
*/
//化妆,互相持有对方的锁,就是需要拿到对方的资源
// private void makeup() throws InterruptedException {
//if (chice == 0) {
// synchronized (lipstick) { //拿到口红的锁
// System.out.println(this.girlName + "拿到了口红的锁");
// Thread.sleep(1000);
// }
// synchronized (mirror) { //一秒后,拿到镜子的锁
// System.out.println(this.girlName + "拿到了镜子的锁");
// }
// } else {
// synchronized (mirror) { //拿到镜子的锁
// System.out.println(this.girlName+ "拿到了镜子的锁");
// Thread.sleep(2000);
// }
// synchronized (lipstick) { //一秒后,拿到口红的锁
// System.out.println(this.girlName + "拿到了口红的锁");
// }
// }
//}
死锁避免方法(只要破坏其中一个或多个死锁的条件就可以避免死锁发生)
产生死锁的四个必要条件:
(1).互斥条件:一个资源每次只能被一个进程使用。
(2).请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不变。
(3).不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
(4).循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
**Lock(锁)**
从JDK 5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁,释放锁。
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable {
int ticketNums = 10;
//定义Lock锁
ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
reentrantLock.lock(); // 加锁
if (ticketNums > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
System.out.println("票卖完了!");
break;
}
} finally {
reentrantLock.unlock(); //释放锁
}
}
}
}
synchronized 与 Lock 的对比:
- Lock是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动
- Lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
- 优先使用顺序: Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)
**线程通信**
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
对于生产者,没有生产产品之前,要通知消费者等待。而生产了产品之后,又需要马上通知消费者消费。
对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费。
在生产者消费者问题中,仅有synchronized是不够的
- synchronized可阻止并发更新同一个共享资源,实现同步。
- synchronized不能用来实现不同线程之间的消息传递(通信)
Java提供了几个方法解决线程之间的通信问题
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常lllegalMonitorStateException
解决方式
1.并发协作模型“生产者/消费者模式”—>管程法
生产者:负责生产数据的模块(可能是方法,对象,线程,进程);
消费者:负责处理数据的模块(可能是方法,对象,线程,进程);
缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区”
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿数据
//测试:生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Productor extends Thread {
SynContainer synContainer;
public Productor(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synContainer.push(new Chicken((i + 1)));
System.out.println("生产了" + (i + 1) + "只鸡");
}
}
}
//消费者
class Consumer extends Thread {
SynContainer synContainer;
public Consumer(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了" + synContainer.pop().id + "只鸡");
}
}
}
//产品
class Chicken {
int id = 10; //生产的总数
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken) {
//如果容器满了,就需要等待消费
if (count == chickens.length) {
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
public synchronized Chicken pop() {
//判断能否消费
if (count == 0) {
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
2.并发协作模型“生产者/消费者模式”—>信号灯法
//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPc2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者-->演员
class Player extends Thread {
TV tv;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
tv.play("快乐大本营播放中");
} else {
tv.play("抖音:记录美好生活!");
}
}
}
}
//消费者-->观众
class Watcher extends Thread {
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品-->节目
class TV {
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice; //表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了" + voice);
//通知观众观看
this.notifyAll(); //通知唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了" + voice);
this.notifyAll(); //通知演员表演
this.flag = !this.flag;
}
}
线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的共享单车。
好处:
(1).提高响应速度(减少了创建新线程的是时间)
(2).降低资源消耗(重复利用线程池中线程,不需要每次都创建)
(3).便于线程管理(…)
<1>. corePoolSize:核心池的大小
<2>. maximumPoolSize:最大线程数
<3>. keepAliveTime:线程没有任务是最多保持多长时间后会终止
**使用方法**
JDK5.0起提供了线程池相关API:ExecutorService和Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
(1). void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
(2). Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
(3). void shutdown():关闭连接池
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
总结
线程实现的三个方法
//回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start(); //1.继承Thread类 的 启动方法
new Thread(new MyThread2()).start(); //2.实现Runnable接口 的 启动方法
FutureTask<Integer> futureTask=new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("myThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("myThread2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("myThread3");
return 100;
}
}
其他看上面