sleep():让当前线程休眠,参数单位为ms,相当于原地踏步
// 用多线程的第二种创建方式
Thread thread = new Thread(() -> {
System.out.println("-----执行线程休眠-----");
System.out.println("休眠前的时间戳:" + System.currentTimeMillis());
try {
// 休眠3000ms
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("休眠后的时间戳:" + System.currentTimeMillis());
});
// 启动线程
thread.start();
join():让使用当前方法的线程优先执行,相当于插队
线程未插队(调用join()方法)前,main线程的内容总是先执行(博主执行了多次,都是main方法的内容在前,未发现线程一先于main线程的情况)
// 用多线程的第二种创建方式
Thread t1 = new Thread(() -> {
System.out.println("线程一");
});
// 启动该线程
t1.start();
System.out.println("main线程");
线程一插队后
// 用多线程的第二种创建方式
Thread t1 = new Thread(() -> {
System.out.println("线程一");
});
// 启动该线程,并让这个线程插队执行
t1.start();
t1.join();
System.out.println("main线程");