Java中建立线程有三种,分别为实现Runnable接口,继承Thread类,实现Callable接口。java
1.Threadide
public class MyThread extends Thread { public MyThread() { this.setName("MyThread"); } public void run() { while(true){ System.out.println("当前运行的线程: "+this.getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String []args){ new MyThread().start(); } }
2.Runnable接口this
public class RunnableTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (true) { System.out.println("当前运行的线程: " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { RunnableTask task = new RunnableTask(); new Thread(task).start(); new Thread(task).start(); } }
以上两种方式没有返回值。线程
3.Callable接口code
public class CallableTest { public static void main(String []args) throws Exception { Callable<Integer> call = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("thread start.."); Thread.sleep(2000); return 1; } }; FutureTask<Integer> task = new FutureTask<>(call); Thread t = new Thread(task); t.start(); System.out.println("do other thing.."); System.out.println("拿到线程的执行结果 : " + task.get()); } }
控制台输出:继承
do other thing.. thread start.. 拿到线程的执行结果 : 1
Callable和Runnable的区别:接口