创建线程5种方法
1、继承Thread,重写run方法,调用start启动
2、实现Runnable接口,重写run方法,调用start启动。
3、lambda表达式
public class MyThread { static class MyExtend extends Thread{ @Override public void run() { System.out.println("Thread"); } } static class MyRun implements Runnable{ @Override public void run() { System.out.println("Thread"); } } public static void main(String[] args) { new MyExtend().start(); new Thread(new MyRun()).start(); new Thread(()->{ System.out.println("Thread"); }).start(); } }
4、对于继承Thread和实现Runnable哪种更好?
实现更好,java是单继承多实现的
5、线程池创建线程
ExecutorService service = Executors.newCachedThreadPool(); service.execute(()->{ System.out.println("Thread"); }); service.shutdown();
6、实现Callable接口
因为实现Runnale接口返回值是写死的void,不灵活,Callable接口返回值可以自己设定
public class MyCallable implements Callable<String > { @Override public String call() throws Exception { return "success"; } public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService service = Executors.newCachedThreadPool(); Future<String> submit = service.submit(new MyCallable()); String s = submit.get(); System.out.println(s); service.shutdown(); } }
作者:http://cnblogs.com/lyc-code/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权力。