栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java线程基本使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java线程基本使用

目录

0. 碎碎念,实现方法

1. Cat线程类

2. 测试main方法

3. 测试结果


0. 碎碎念,实现方法

0.1. 继承Thread类, 重写run方法。

0.2. 继承Runable类,重写run方法。

Thread结构图

 1.当一个类继承了Thread, 该类就可以当作一个线程使用
 2.重写run方法,加上自己的业务逻辑
 3.thread类实现Runable接口的方法

1. Cat线程类
public class Cat extends Thread {
    //当一个类继承了Thread, 该类就可以当作一个线程使用
    @Override
    public void run() {
        int times = 0;
        while (true){
            //每隔一秒在控制台输出小猫
            System.out.println("hello,我是小猫猫" + (++times));
            //让该线程休眠1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (times==20){ //当线程执行到20次时候,结束循环。
                break;
            }
        }
    }
}

2. 测试main方法
public class Thread01 {
    public static void main(String[] args) {
        //创建cat, 可以当作线程使用
        Cat cat = new Cat();
        //启动线程
        cat.start();
    }
}

3. 测试结果

hello,我是小猫猫1
hello,我是小猫猫2
hello,我是小猫猫3
hello,我是小猫猫4
hello,我是小猫猫5
hello,我是小猫猫6
hello,我是小猫猫7
hello,我是小猫猫8
hello,我是小猫猫9
hello,我是小猫猫10
hello,我是小猫猫11
hello,我是小猫猫12
hello,我是小猫猫13
hello,我是小猫猫14
hello,我是小猫猫15
hello,我是小猫猫16
hello,我是小猫猫17
hello,我是小猫猫18
hello,我是小猫猫19
hello,我是小猫猫20

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/888593.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号