实现多线程编程的两种方式

1. 继承Thread类 (Thread类实现了Runnable接口:public class Thread implements Runnable)
2. 实现Runnable接口

实例代码:
1. 继承Thread类

public class MyThreadDemo {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

class MyThread extends Thread{
    @Override
    public void run(){
        //run方法
    }
}

2. 实现Runnable接口
(1) 方法一

public class MyThreadDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run(){
                //run方法
            }
        });
        thread.start();
    }
}

(2) 方法二

public class MyThreadDemo {
    public static void main(String[] args) {
        Runner one = new Runner();
        Thread thread = new Thread(one); //都是接收了一个实现了Runnable的对象
        thread.start();
    }
}

class Runner implements Runnable{
    @Override
    public void run(){
        //run方法
    }
}

猜你喜欢

转载自www.cnblogs.com/zeroingToOne/p/9064123.html