Java中创建线程主要有三种方式,分别为继承Thread类、实现Runnable接口、实现 Callable接口。
一、继承Thread类
继承Thread类,重写run()方法,调用start()方法启动线程
public class ThreadTest{
public static class MyThread extends Thread{
@Override
public void run{
System.out.println("extends Thread")
}
}
public static void main(String[] args){
Mythread mythread = new Mythread();
mythread.start();
}
}
二、实现Runnable接口
实现 Runnable 接口,重写run()方法
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("MyRunnable is " + name);
}
}
public class Test1 {
public static void main(String[] args){
MyRunnable myRunnable1=new MyRunnable("Runnable1");
new Thread(myRunnable1).start();
}
}
三、实现Callable接口
上面两种都是没有返回值的,但是如果我们需要获取线程的执行结果,该怎么办呢?
实现Callable接口,重写call()方法,这种方式可以通过FutureTask获取任务执行的返回值
public class CallerTask implements Callable<String>{
public String call() throws Exception{
return "I am running."
}
public static void main(String[] args){
FutureTask<String> task = new FutureTask<String>(new CallerTask());
new Thread(task).start();
try {
//等待执行完成,并获取返回结果
String result=task.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
标签:MyRunnable,String,Thread,创建,void,三种,进程,new,public
From: https://blog.51cto.com/u_16269508/7579704