Java多线程实现优缺点_创建线程的三种方式及其优缺点

packagetestA;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.FutureTask;public classThreadTest {public static voidmain(String[] args) {//1.继承Thread类

newDefineThread().start();//2.实现Runnable接口

new Thread(newDefineRunnable()).start();//3.实现Callable接口

newThread(futureTask).start();

String result= "";try{

result=futureTask.get();

}catch(InterruptedException e) {

e.printStackTrace();

}catch(ExecutionException e) {

e.printStackTrace();

}

System.out.println(result);

}static class DefineThread extendsThread {

@Overridepublic voidrun() {for (int i = 0; i < 100; i++) {

String name2=getName();try{

sleep(100);

}catch(InterruptedException e) {

e.printStackTrace();

}

System.out.println(name2+ ": " +i);

}

}

}static class DefineRunnable implementsRunnable {

@Overridepublic voidrun() {for (int i = 0; i < 100; i++) {//String name2 = getName();

String name = Thread.currentThread().getName(); //实现runnable接口,使用Thread类的currentThread()获取当前线程对象

try{

Thread.currentThread().sleep(100);

}catch(InterruptedException e) {

e.printStackTrace();

}

System.out.println(name+ ": " +i);

}

}

}static FutureTask futureTask = new FutureTask<>(new Callable() {

@Overridepublic String call() throwsInterruptedException {

String name= "";int i = 0;for (; i < 100; i++) {

name=Thread.currentThread().getName();

Thread.currentThread().sleep(100);

System.out.println(name+ ": " +i);

}return name + " ----->Result=" +i;

}

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值