怎么在java中实现线程

   2025-02-05 6480
核心提示:在Java中,可以通过以下两种方式来实现线程:继承Thread类:public class MyThread extends Thread {@Overridepublic void run()

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

继承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(); // 启动线程    }}
实现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()方法来启动线程。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言