21xrx.com
2025-04-12 13:40:27 Saturday
文章检索 我的文章 写文章
Java线程的创建方法
2023-06-11 02:24:22 深夜i     6     0
Java线程 继承 实现 代码示例

在Java中,有两种方式可以创建线程。第一种是继承Thread类,并实现run()方法;第二种是实现Runnable接口,并将其实例化为Thread类的一个对象。以下是我分享的代码示例:

1. 继承Thread类:

public class MyThread extends Thread {
  public void run() {
    System.out.println("This is a thread created by extending Thread class.");
  }
}
// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();

2. 实现Runnable接口:

public class MyRunnable implements Runnable {
  public void run() {
    System.out.println("This is a thread created by implementing Runnable interface.");
  }
}
// 创建并启动线程
MyRunnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);
myThread.start();

  
  

评论区

请求出错了