Linux 拨号vps windows公众号手机端

怎么在java中实现线程

lewis 8年前 (2017-04-26) 阅读数 10 #程序编程
文章标签 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()方法来启动线程。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门