Java 创建线程的三种方式分别是:继承Thread类、实现Runnable接口和实现Callable接口;
1.继承Thread类示例
public class StartThread extends Thread{ @Override public void run() { System.out.println("thread线程创建"); System.out.println("thread --> "+Thread.currentThread().getName()); } public static void main(String[] args) { StartThread st=new StartThread(); st.start(); System.out.println("main --> "+Thread.currentThread().getName()); } }
2.实现Runnable接口示例
public class StartRunnable implements Runnable { @Override public void run() { System.out.println("thread线程创建"); System.out.println("thread --> "+Thread.currentThread().getName()); } public static void main(String[] args) { StartRunnable sr=new StartRunnable(); Thread t=new Thread(sr,"zaza"); t.start(); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main --> "+Thread.currentThread().getName()); } }
3.实现Callable接口示例
public class StartCallable implements Callable { @Override public Object call() throws Exception { System.out.println("thread --> "+Thread.currentThread().getName()); return null; } public static void main(String[] args) { StartCallable sc=new StartCallable(); ExecutorService executorService= Executors.newFixedThreadPool(2); Future future1=executorService.submit(sc); Future future2=executorService.submit(sc); System.out.println(future2.isDone()); System.out.println("main --> "+Thread.currentThread().getName()); executorService.shutdown(); } }
三种方式对比
1.继承Thread类的方式实现比较简单,但是受限于单继承;
2.实现Runnable、Callable接口比较灵活,不受限于单继承,适合多个线程进行资源共享,同时增强了程序的扩展性,降低了程序的耦合性;实现类中,运行Callable任务可以拿到一个Future对象,通过Future对象可以了解任务执行情况;
Runnable类:
@FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }
Callable类
@FunctionalInterface public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }
————————————————
版权声明:本文为CSDN博主「longshengguoji」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/longshengguoji/article/details/41126119