Java线程开启的三种方式
第一种 继承Thread
public class ThreadDemo extends Thread{ @Override public void run() { System.out.println("开启线程"); } }
public class test { public static void main(String[] args) { ThreadDemo td = new ThreadDemo(); td.start(); } }
第二种 通过Runnable接口
//实现Runnable接口 public class MyThread implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + "开启" + i); } } }
public class test { public static void main(String[] args) { MyThread mt = new MyThread(); Thread thread = new Thread(mt); thread.setName("一条线程"); thread.start(); } }
第三种 实现Callable接口
public class callableDemo implements Callable<String> { @Override public String call() throws Exception { for (int i = 0; i < 100; i++) { System.out.println("你爱我吗?"); } return "我爱你"; } }
public class test { public static void main(String[] args) throws ExecutionException, InterruptedException { callableDemo cd = new callableDemo(); FutureTask<String> sf = new FutureTask<String>(cd); Thread thread = new Thread(sf); thread.start(); String s = sf.get(); //线程结束后,获取返回结果 System.out.println(s); } }