Java程序员多线程部分之了解我们的多线程(初学者适用)

一、多线程的使用

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();
    }

经过对比可以看出,单进程多线程明显提高了效率。使用了多线程之后,整个程序的效率被大大提高 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值