盘点一下Java中创建线程的几种方式
一、继承Thread类,重写run()方法
public class MyThread extends Thread { @Override public void run() { System.out.println("my thread start " + Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println("main thread start "+Thread.currentThread().getName()); MyThread myThread = new MyThread(); myThread.start(); } }
二、实现Runnable接口,并重写run()方法
public class MyThreadRunnable implements Runnable { @Override public void run() { System.out.println("my thread start " + Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println("main thread start " + Thread.currentThread().getName()); MyThreadRunnable myThreadRunnable = new MyThreadRunnable(); Thread thread = new Thread(myThreadRunnable); thread.start(); } }
三、实现Callable接口,并重写call()方法
public class MyThreadCallable implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("my thread start " + Thread.currentThread().getName()); Integer ret = 0; for (int i = 0; i < 10; i++) { ret += i; } return ret; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyThreadCallable myThreadCallable = new MyThreadCallable(); FutureTask<Integer> futureTask = new FutureTask<>(myThreadCallable); Thread thread = new Thread(futureTask, "A"); thread.start(); int ret = futureTask.get(); System.out.println("main thread ret = " + ret + " " + Thread.currentThread().getName()); } }
综上,类图关系如下:
标签:Java,Thread,thread,System,几种,start,currentThread,线程,public From: https://www.cnblogs.com/damour-damocles/p/18606974