java线程启动的三种方式
Posted Muche
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程启动的三种方式相关的知识,希望对你有一定的参考价值。
java线程启动的三种方式
原生的Thread,Runable和借助concurent包中的Callable与FutureTask,实现有返回值的线程
import org.omg.PortableServer.THREAD_POLICY_ID;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* 实现Thread的几种方法
*/
public class ThreadTest{
public static void main (String[] args) throws Exception {
thread t = new thread("thread");
t.start();
Thread r = new Thread(new runnableThread(), "runnable");
r.start();
FutureTask<Integer> task = new FutureTask<>(new callable());
Thread c = new Thread(task, "callable");
c.start();
System.out.println("返回值" + task.get());
}
}
class thread extends Thread{
public thread(String name){
super(name);
}
@Override
public void run() {
System.out.println(currentThread().getName() + "启动了");
System.out.println("------------------------------------");
}
}
class runnableThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "启动了");
System.out.println("------------------------------------");
}
}
class callable implements Callable<Integer>{
private int i = 1;
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + "启动了");
return i;
}
}
以上是关于java线程启动的三种方式的主要内容,如果未能解决你的问题,请参考以下文章