目录
1.线程休眠演示打印电影字幕
public class ThreadDemo1 {
public static void main(String[] args) throws InterruptedException {
String content = "后来你会慢慢明白,任何时候都会过去的。绝望的时候,它也就是这样一段时间,就过去了。愉悦得像沐浴在金色的阳光里,它也就是一段时间,它也会过去的。到后来你会努力绝望的时候不那么绝望,高兴的时候也不要那么高兴,是你慢慢会学会的。";
for(char item : content.toCharArray()) {
System.out.print(item);
Thread.sleep(500);
}
}
}
2.多线程 VS 单线程性能
public class ThreadDemo2 {
//总任务执行次数
private final static int COUNT = 10;
public static void main(String[] args) throws InterruptedException {
//记录开始执行的时间
long stime = System.currentTimeMillis(); //获取当前时间的毫秒数时间戳
//使用单线程进行执行
singleThread();
// //使用多线程进行执行
// multiThread();
//记录结束执行的时间
long etime = System.currentTimeMillis();
System.out.println("执行时间:" + (etime - stime));
}
/**
* 单线程任务执行
*/
private static void singleThread() {
for(int i = 0; i < COUNT; i++) {
try {
//每次方法执行需要1s(伪代码)
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 多线程任务执行
*/
private static void multiThread() throws InterruptedException {
Thread t = new Thread(() -> {
for(int i = 0; i < COUNT / 2; i++) {
try {
//每次方法执行需要1s(伪代码)
Thread.sleep(1000);
System.out.println("新线程:执行了for循环:" + LocalDateTime.now());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//开始执行线程
t.start();
//主线程也进行任务的执行
for(int i = 0; i < COUNT / 2; i++) {
try {
//每次方法执行需要1s(伪代码)
Thread.sleep(1000);
System.out.println("主线程:执行了for循环:" + LocalDateTime.now());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//等待新线程执行完之后继续去执行
t.join();
}
}
单线程执行任务所需时间:
多线程(2个线程)执行任务所需时间:
使用了多线程之后,整个程序的执行效率大大提高。