租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

如何在java中实现线程,如何在JAVA中实现线程

发布时间:2024-01-09 23:32:16

如何在java中实现线程

在Java中,可以通过以下两种方式来实现线程:

  1. 继承Thread类:
public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程履行的代码
        System.out.println("线程运行中");
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start(); // 启动线程
    }
}
  1. 实现Runnable接口:
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程履行的代码
        System.out.println("线程运行中");
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start(); // 启动线程
    }
}

不管是继承Thread类或实现Runnable接口,都需要重写run()方法,该方法中定义线程要履行的代码。然后通过创建线程对象,并调用start()方法来启动线程。