java继承Thead类和实现Runnable接口创建线程的区别

一、继承Thread类创建多线程

public class Demo{
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
    
}
class MyThread extends Thread{
    @Override
    public void run() {
        //子线程执行的操作
    }
}

注意:开启子线程要调用start()方法而不是调用run方法

二、实现Runnable接口创建多线程

public class Demo{
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }

}
class MyRunnable implements Runnable{
    @Override
    public void run() {
        //子线程执行的操作
    }
}

第二种方式相对于第一种方式有哪些优势:

1、避免java单继承带来的局限性(第一种方式继承Thread类后就不能继承别的类,从而给程序扩展带来不便)

2、第一种方式不能实现线程类变量共享,而第二种方式可以,例如下面这种情况

public class Demo{
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();
        thread1.start();
        thread2.start();
        thread3.start();
    }

}
class MyThread implements Thread{
    int count = 10;
    @Override
    public void run() {
        //子线程执行的操作
        count--;
    }
}

由于不同的线程对象,有不同的内存副本,导致count–只是操作当前线程对象中的count不会影响其他线程,从而导致无法共享变量。

改进方式如下

public class Demo{
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        Thread thread3 = new Thread(runnable);
        thread1.start();
        thread2.start();
        thread3.start();
    }

}
class MyRunnable implements Runnable{
    int count = 10;
    @Override
    public void run() {
        //子线程执行的操作
        count --;
    }
}

上面代码实现了count变量的共享,但要注意线程安全问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值