多线程


package threaduse;

/**
 * Copyright (C), 2018-2021, Mr.Lin
 * Author: Mr.Lin
 * Date: 2021/11/27 1:38
 * FileName: Thread02
 * Description:通过实现接口Runnable 来开发线程
 */
public class Thread02 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        //不能调用start
        Thread thread = new Thread(dog);
        thread.start();
    }
}
class Dog implements Runnable{

    @Override
    public void run() {
        int count=0;
        while (true) {
            System.out.println("小狗嗡嗡叫----"+(++count)+Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(count==10){break;}
        }
    }
}

 

package threaduse;

/**
 * Copyright (C), 2018-2021, Mr.Lin
 * Author: Mr.Lin
 * Date: 2021/11/27 0:57
 * FileName: Thread01
 * Description: 演示通过thread类创建线程
 */
public class Thread01 {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.start();
    }
}
//1.当一个类继承了Thread类该类就可以当作线程使用
class Cat extends Thread {
    @Override
    public void run() {//重写run方法写上自己的逻辑
        int times=0;
        while (true){
            System.out.println("喵喵喵,我是猫咪"+(++times));
            //休眠一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(times==8){
                System.out.println("退出线程");
                break;
            }
        }

    }
}

 线程的状态:

 

posted @ 2021-11-27 01:10  骄傲的林先生  阅读(21)  评论(0)    收藏  举报