多线程的其中两种创建方法

实现多线程的其中两种方法:

1.继承Thread类

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i%2==0){
                System.out.println("子线程-------------->"+i);
            }
        }
    }
}

首先定义一个类让它继承Thread类,重写run方法

public class Test {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        for (int i = 0; i < 100; i++) {
            if(i%2==0){
                System.out.println("主线程---------->"+i);
            }
        }
    }
}

在测试类中创建一个对象,并且调用start方法,并且在主线程中也写一段程序,我们运行程序,看一下结果

 两个程序输出的结果交替输出,说明在宏观上两个程序是并发的

2.实现Runnable接口

public class RunThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if(i%2!=0){
                System.out.println("子线程----------->"+ i);
            }
        }
    }
}

首先编写一个类,使它实现Runnable方法,重写run方法

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new RunThread());

        thread.start();

        for (int i = 0; i < 100; i++) {
            if(i%2!=0){
                System.out.println("主线程--------->"+i);
            }
        }
    }
}

在测试类中创建一个Thread对象,调用start方法,运行结果如下:

 可以看到程序也是并发执行的,效果和我们继承Thread类是一致的。

 如果有复杂的线程操作需求,那就选择继承Thread,如果只是简单的执行一个任务,那就实现runnable。

猜你喜欢

转载自blog.csdn.net/weixin_65379795/article/details/130058981
今日推荐