Linux 拨号vps windows公众号手机端

java中多线程的使用方法是什么

lewis 9年前 (2016-08-16) 阅读数 8 #程序编程
文章标签 Java

Java中多线程的使用方法有两种:一种是通过继承Thread类来创建线程,另一种是通过实现Runnable接口来创建线程。

  1. 通过继承Thread类来创建线程:
class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        
        thread1.start();
        thread2.start();
    }
}
  1. 通过实现Runnable接口来创建线程:
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程执行的代码
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable);
        Thread thread2 = new Thread(myRunnable);
        
        thread1.start();
        thread2.start();
    }
}

这两种方法都可以用来创建多个线程,并且在start()方法调用后,线程会异步执行。在实际应用中,一般推荐使用实现Runnable接口的方式来创建线程,因为Java不支持多重继承,而通过实现Runnable接口可以避免这个限制。

版权声明

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

发表评论:

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

热门