欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java实现Runnable接口实现多线程

程序员文章站 2022-05-05 16:56:02
...

1、新建一个类并实现Runnable接口

class MyThread implements Runnable {
    private String title;

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

public class TestThread {
    public static void main(String[] args) {

    }
}

2、覆写Runnable接口中的run()方法(线程的主体方法)

class MyThread extends Thread {
    private String title;

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

    public void run() {
        for (int x = 0; x < 100; x++) {
            System.out.println(this.title + "运行,x =" + x);
        }
    }
}

public class TestThread {
    public static void main(String[] args) {

    }
}

3、启动多线程必须使用start()方法,而Runnable接口中并没有start()方法,需要使用Thread类构造方法来调用start()方法启动多线程

class MyThread extends Thread {
    private String title;

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

    public void run() {
        for (int x = 0; x < 100; x++) {
            System.out.println(this.title + "运行,x =" + x);
        }
    }
}

public class TestThread{
    public static void main(String[] args) {
        Thread thread1 = new Thread( new MyThread("线程1"));
        Thread thread2 = new Thread( new MyThread("线程2"));
        Thread thread3 = new Thread( new MyThread("线程3"));
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

结果如下图所示
Java实现Runnable接口实现多线程