Java Runnable 如何实现多线程

发布时间:2025-01-23 22:52:39 作者:小樊
来源:亿速云 阅读:101

在Java中,要实现多线程,可以通过实现Runnable接口或者继承Thread类。下面是两种方法的示例:

  1. 实现Runnable接口:
public class MyRunnable implements Runnable {
    private String threadName;

    public MyRunnable(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(threadName + ":" + i);
        }
    }

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable("线程1");
        Thread thread1 = new Thread(runnable);
        thread1.start();

        MyRunnable runnable2 = new MyRunnable("线程2");
        Thread thread2 = new Thread(runnable2);
        thread2.start();
    }
}
  1. 继承Thread类:
public class MyThread extends Thread {
    private String threadName;

    public MyThread(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(threadName + ":" + i);
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread("线程1");
        Thread thread1 = new Thread(myThread);
        thread1.start();

        MyThread myThread2 = new MyThread("线程2");
        Thread thread2 = new Thread(myThread2);
        thread2.start();
    }
}

在这两个示例中,我们创建了两个线程,每个线程执行run方法中的代码。main方法中,我们创建了RunnableThread对象,并将其传递给Thread类的构造函数。然后调用start()方法启动线程。这将导致线程并行执行run方法中的代码。

推荐阅读:
  1. java 多线程-Runnable接口
  2. 多线程在java中的使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:服务器在DNSSEC下的应急响应计划如何制定

下一篇:Runnable 接口在 Java 中如何工作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》