3种实现:thread、runnable、callable
1、thread
@Slf4j public class MyThread extends Thread { @Override public void run() { log.info("线程ID:{}",Thread.currentThread().getId()); } } public class MyTest { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }
输出:10:09:08.152 [Thread-0] INFO c.e.thread.MyThread:9 - 线程ID:10
2、runnable
@Slf4j public class MyRunnable implements Runnable { public MyRunnable() { } @Override public void run() { log.info("线程ID:{}",Thread.currentThread().getId()); } } public class MyTest { public static void main(String[] args) { MyRunnable r = new MyRunnable(); new Thread(r).start(); } }
输出:10:09:20.272 [Thread-0] INFO c.e.r.MyRunnable:10 - 线程ID:10
3、callable
import java.util.concurrent.Callable; public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i < 10000*100; i++) { sum = sum +1; } return sum; } } import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import lombok.extern.slf4j.Slf4j; @Slf4j public class MyTest { public static void main(String[] args) { MyCallable c = new MyCallable(); FutureTask<Integer> result = new FutureTask<>(c); new Thread(result).start(); try { Integer sum = result.get(); log.info("{}",sum); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
输出:10:08:49.349 [main] INFO c.e.callable.MyTest:15 - 1000000