Java学习 Day01 多线程

文章封面

Java学习 Day01 多线程

Java多线程实现方式有 2 种

1.继承 Thread 类,重写 run 方法

  • 案例
  • 测试类 Thread01
    package top.wanqq.thread;
    

/**

  • @author wanqq
  • / public class Thread01 extends Thread { @Override public void run() {
      for (int i = 0; i < 200; i++) {
          System.out.println("-------" + i);
          try {
              Thread.sleep(1);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
    } }
- 主类 ThreadIndex 
```Java
package top.wanqq.thread;

/**
 * @author wanqq
 */
public class ThreadIndex {
    public static void main(String[] args) {
        new Thread01().start();
        for (int i = 0; i < 200; i++) {
            System.out.println("Thread index :" + i);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 结果
  • image

    2.实现 Runnable 接口

  • 测试类 RunnableThreadTest
    package top.wanqq.thread;
    

/**

  • @author wanqq

  • / public class RunnableThreadTest implements Runnable{

    @Override public void run() {

      for (int i = 0; i < 10; i++) {
          System.out.println("runnable test :" + i);
          try {
              Thread.sleep(1);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }

    } }

- 主类 ThreadIndex 
```java 
package top.wanqq.thread;

/**
 * @author wanqq
 */
public class ThreadIndex {
    public static void main(String[] args) {
        new Thread(new RunnableThreadTest()).start();
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread index :" + i);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 结果
  • image

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0