实现多线程的四种方式总结

1.继承Thread类

public class Mythread extends Thread{
public void run(){
//执行的方法体
System.out.println("mythread is running...");
}
public static void main(String[] args){
Mythread t1=new Mythread();
t1.start();
}
}

2.实现Runnable接口

public class Mythread implements Runnable{
public void run(){
//执行的方法体
System.out.println("mythread is running...");
}
public static void main(String[] args){
Mythread t1=new Mythread();
Thread t2=new Thread(t1);
// 或者  Thread t2=new Thread(new Mythread());
t2.start();
}
}

3.通过Callable和FutrueTask类实现

public class Mythread implements Callable{
public Object call(){
//执行的方法体,返回值通过t2.get得到
return null;
}
public static void main(String[] args){
Mythread t1=new Mythread();
FutureTask t2=new FutureTask(t1);
Thread t3=new Thread(t2);
t3.start();
}
}

4.通过线程池来创建线程

Executors.newSingleThreadExecutor();//创建容量为1的缓冲池

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值