一、多线程的使用
1.多线程来打印电视剧旁白
package thread.threaddemo;
/**
* @Author: wenjingyuan
* @Date: 2022/10/31/20:32
* @Description:使用线程实现电影旁白的打印
*/
public class ThreadDemo1 {
public static void main(String[] args) throws InterruptedException {
String content="我想要你知道,这个世界会一直有人爱你,你不是尘埃,是天上那颗最亮的星星。";
for(char item: content.toCharArray()){
System.out.print(item);
Thread.sleep(100);
}
}
}
2.多线程和单线程的对比
- 单线程代码以及输出结果
package thread.threaddemo;
/**
* @Author: wenjingyuan
* @Date: 2022/10/31/21:13
* @Description:
*/
public class ThreadDemo2 {
private static final int COUNT=10;
public static void main(String[] args) {
//记录开始执行方法的时间戳
long stime=System.currentTimeMillis();
singleThread();
//记录结束执行方法的时间戳
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 mutiThread() throws InterruptedException {
//创建一个新线程
Thread thread=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();
}
}
});
//启动新线程
thread.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();
}
}
//等两个线程同时结束之后在记录时间
thread.join();
}
经过对比可以看出,单进程多线程明显提高了效率。使用了多线程之后,整个程序的效率被大大提高 。