java多线程的实现方式

1.继承Thread类,重写run()方法
2.实现Runnable接口,实现run()方法

继承Thread类

package thread;

public class Demo1_Thread {
    public static void main(String[] args) {
        //创建Thread的子类对象
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        //开启线程
        t1.start();       
        t2.start();
    }
}
//1.继承Thread
class MyThread extends Thread{
    @Override              //2.重写run()方法
    public void run() {    //3.将要执行的代码,写在run()方法里面
        while(true) {
            System.out.println(getId()+"..."+getName());
        }
    }
}

运行结果如下

10...Thread-0
11...Thread-1
11...Thread-1
10...Thread-0
10...Thread-0
11...Thread-1
11...Thread-1
10...Thread-0
10...Thread-0

实现Runnable接口


package thread;

public class Demo2_Thread {
    public static void main(String[] args) {
        //创建Runable子类对象
        Runnable r = new MyRunable();
        //将子类对象传入Thread类的构造方法中
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        //开启线程
        t1.start();
        t2.start();
    }
}
//1.实现Runable接口
class MyRunable implements Runnable{
    @Override              //2.实现run()方法
    public void run() {    //3.将要执行的代码,写在run()方法里面
        while(true) {
            System.out.println(Thread.currentThread().getName()+" start...");
        }
    }

}

运行结果如下

Thread-1 start...
Thread-1 start...
Thread-0 start...
Thread-0 start...
Thread-0 start...
Thread-0 start...
Thread-1 start...
Thread-1 start...
Thread-1 start...

两种方式对比:由于java是单继承多实现,所以继承Thread要确保该类没有父类,而实现Runnble接口的子类无法直接使用Thread类的方法和属性,需要通过Thread类.currentThread()方式获得正在运行线程的引用

猜你喜欢

转载自blog.csdn.net/zhblanlan/article/details/80811903