多线程(一):认识线程,创建线程和线程的常用方法

概念

进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。每个进程至少有一个线程存在,即主线程。
在这里插入图片描述

例程:实现字符缓慢输出

public class ThreadDemo1 {
   
    public static void main(String[] args) throws InterruptedException {
   
        String content = "别人说你不行,是因为他自己做不到。你要尽全力保护你的梦想,那些嘲笑你的人,他们必定会失败," +
                "他们想把你变成和他们一样的人。如果你有梦想的话,就要努力去实现, 就这样。";
        for (char item : content.toCharArray()) {
   
            System.out.print(item);
            //执行到此行休眠200毫秒
            Thread.sleep(200);
        }
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

多线程的优势-增加运行速度

可以观察下面这个多线程例程,体验多线程时如何怎加运行速度的。

public class ThreadDemo2 {
   

    //执行的循环次数
    private static final Long count = 5_0000_0000L;

    public static void main(String[] args) throws InterruptedException {
   

//        System.out.println(Thread.currentThread().getName());

        //调用多线程的方法
        concorrency();

        //调用单线程的方法
        serial();
    }

    //单线程的方法
    private static void serial() {
   
        //记录开始时间
        Long stime = System.currentTimeMillis();//记录当前时间的毫秒时间戳
//        System.nanoTime();//当前时间的纳秒时间戳(更精确)
        int a = 0;
        //执行15亿次循环
        for (int i = 0; i < 3 * count; i++) {
   
            a++;
        }
        //记录结束时间
        Long etime = System.currentTimeMillis();
        System.out.println("单线程执行了: " + (etime - stime));
    }

    //多线程的方法
    private static void concorrency() throws InterruptedException {
   
        //开始时间
        Long stime = System.currentTimeMillis();

        //执行15亿次循环
        //创建了线程任务
        Thread t1 = new Thread(new Runnable() {
   
            @Override
            public void run() {
   
                //具体业务
                int a = 0;
                for (int i = 0; i < count; i++) 
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值