继承Thread 类

 public class ThreadTest {
     public static void main(String[] args) throws InterruptedException {
         //创建 Cat 对象,可以当做线程使用
         Thread cat = new Cat();
         cat.start(); // start 方法才是真正线程的启动方法,start方法---->start0()本地方法,该start0方法是由JVM执行,实现多线程的效果

         // cat.run(); run 方法就是一个普通的方法, 没有真正的启动一个线程,


         for (int i = 1; i <= 60 ; i++) {
             System.out.println("主线程:" + Thread.currentThread().getName()+"继续执行: "+i);
             Thread.sleep(1000);
         }
     }
 }
  // Cat为线程类
  class Cat extends Thread{
            int times = 0;
            @Override
            public void run() {
                while (true){
                    System.out.println("喵喵, 我是小猫咪" + (++times) + " 线程名=" + Thread.currentThread().getName());
                    try {
                        // 让该线程休眠 1 秒
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    if(times == 80){
                        break; //当 times 到 80, 退出 while, 这时线程也就退出
                    }
                }
            }
 }
posted @ 2024-05-20 22:49  jock_javaEE  阅读(19)  评论(0)    收藏  举报