以Thread创建线程为例:
1 Thread thread = new Thread() { 2 @Override 3 public void run() { 4 log.info("create and start a thread through creating a Thread Object"); 5 } 6 }; 7thread. start();
跟踪start()方法的源码
1 public synchronized void start() { 2 /** 3 * This method is not invoked for the main method thread or "system" 4 * group threads created/set up by the VM. Any new functionality added 5 * to this method in the future may have to also be added to the VM. 6 * 7 * A zero status value corresponds to state "NEW". 8 */ 9 if (threadStatus != 0) 10 throw new IllegalThreadStateException(); 11 12 /* Notify the group that this thread is about to be started 13 * so that it can be added to the group's list of threads 14 * and the group's unstarted count can be decremented. */ 15 group.add(this); 16 17 boolean started = false; 18 try { 19 start0(); 20 started = true; 21 } finally { 22 try { 23 if (!started) { 24 group.threadStartFailed(this); 25 } 26 } catch (Throwable ignore) { 27 /* do nothing. If start0 threw a Throwable then 28 it will be passed up the call stack */ 29 } 30 } 31 }
发现,实际调用的是start0()方法,而这个方法是一个本地方法;
1 private native void start0();
想要了解这个方法的内部实现,就必须去查看jdk的源码了,是由C++进行实现的
1、Thread类启动线程
1 /**
2 * 通过创建Thread对象创建线程
3 */
4 private static void testCreateThread() {
5 Thread thread = new Thread() {
6 @Override
7 public void run() {
8 log.info("create and start a thread through creating a Thread Object");
9 }
10 };
11 thread. Start();
12 }
2、实现Runable接口
1 /**
2 * 创建和运行线程
3 */
4 @Slf4j(topic = "c.MyThread")
5 public class MyThread02 {
6 public static void main(String[] args) {
7 testCreateThread();
8 }
9
10 /**
11 * 通过实现Runnable接口创建线程
12 */
13 private static void testCreateThread() {
14 Task task = new Task();
15 task.run();
16 }
17 }
18 @Slf4j(topic = "c.Runnable")
19 class Task implements Runnable {
20 @Override
21 public void run() {
22 log.info("create and start a thread through implements Runnable interface");
23 }
24 }
3、FutureTask接口
1 public static void main(String[] args) throws ExecutionException, InterruptedException {
2 // 创建任务对象
3 FutureTask<Integer> futureTask = new FutureTask(() ->{
4 log.debug("hello");
5 Thread.sleep(2000);
6 return 100;
7 });
8 // 创建线程
9 new Thread(futureTask,"t3").start();
10
11 // 主线程阻塞,同步等待futureTask执行完毕的结果
12 Integer result = futureTask.get();
13 log.info("{}",result);
14 }