关于Java线程创建的三种方式:
第一种继承自Thread 类:
public class Threads extends Thread{
public void run(){
super.run();
try{
TimeUnit.SECONDS.sleep(50);
}catch(Exception e){
e.printStackTrace();
}
System.out.print("run");
}
public static void main(String[] args){
System.out.print("main\n");
new Threads().start();
}
}
第二种实现 Runnable接口:
public class Runs implements Runnable{
public void run(){
try{
Thread.sleep(300);
}catch(Exception e){
e.printStackTrace();
}
System.out.print("runnable\n");
}
public static void main(String[] args){
System.out.print("main\n");
new Thread(new Runs()).start();
}
}
第三种实现 Callable接口:
public class Calls implements Callable<String>{
public static void main(String[] args){
Calls c=new Calls();
FutureTask<String> task=new FutureTask<String>(c);
new Thread(task).start();
try {
System.out.print(task.get()+"");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
public String call() throws Exception {
System.out.print("call\n");
return "run";
}
}
这三种实现方式的区别:
第一种方式由于java的单继承性,继承了Thread类就不能继承其他类了,比较尴尬。我们用的最对的是第二种方式,比较方便,但是第二种不能返回线程处理的结果,因此有了第三种方式,得到返回结果。