1 Java中有几种方式创建线程
1 Java中有几种方式创建线程
四种
一 继承 thread 类
public class ZhouyuThread extends Thread{ public static void main(String[] args){ ZhouyuThread thread = new ZhouyuThread(); thread.start(); } @Override public void run(){ System.out.println("hello zhouyu"); } }
重写run方法而不是start方法 缺点单继
二 实现 runnable 接口
public class ZhouyuThread implements Runnable{ public static void main(String[] args){ Thread thread = new Thread (new ZhouyuThread()); thread.start(); } public void run(){ System.out.println("hello zhouyu"); } }
匿名内部类
public class ZhouyuThread { public static void main(String[] args){ Thread thread = new Thread (new Runable(){ public void run(){ System.out.println("hello zhouyu"); } }); thread.start(); } }
runnable是函数式接口 只有一个润方法 可以利用lambda 表达式 这是java8 的行动性
public class ZhouyuThread{ public static void main(String[] args){ Thread thread = new Thread(() -> System.out.print("hello zhouyv")); thread.start(); }
总而言之 实现runnable接口
三 实现 callable 接口
区别 Runnable 这个可以拿到结果
public class ZhouyuThread implements Callable<String> { public static void main(String[] args)throws ExecutionException,InterruptedException{
//FutureTask 接口继承了 Runable 和 Future FutureTask<String> futureTask =new FutureTask<>(new ZhouyuThread()); Thread thread = new Thread (futureTask); thread.start();
//阻塞式拿到结果 没结果当前线程会被挂起 String result = futureTask.get(); System.out.println(result); } @Override public String call(){ return "hello zhouyu"; } }
四 利用线程池创建线程
public class ZhouyuThread implements Runnable { public static void main(String[] args)throws ExecutionException,InterruptedException{ ExecutorService executorService = Executors.newFixedThreadPool(10); executorService .execute(new ZhouyuThread()); } @Override public void run(){ System.out.println("hello zhouyu"); } }