书接上篇一个简单的Thread
首先是一个任务类,这里做具体的业务逻辑,需要什么参数通过构造方法引入
package com.example.demo.threadPool;
public class TestRunable implements Runnable {
@Override
public void run() {
System.out.println("子线程开始");
try{
// 子线程休眠五秒
Thread.sleep(5000);
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("子线程结束");
}
}
调用任务类发起请求,实现主线程无需等待
子线程执行结束
@Test
void a2() throws Exception {
long l = System.currentTimeMillis();
TestRunable testRunable = new TestRunable();
Thread thread = new Thread(testRunable);
thread.start();
System.out.println("主线程执行时长:"+String.valueOf(System.currentTimeMillis()-l));
}
调用任务类发起请求,实现主线程等待
子线程执行结束
@Test
void a2() throws Exception {
long l = System.currentTimeMillis();
TestRunable testRunable = new TestRunable();
Thread thread = new Thread(testRunable);
thread.start();
thread.join();
System.out.println("主线程执行时长:"+String.valueOf(System.currentTimeMillis()-l));
}
其实质跟thread模式创建一样