Java中线程的run()和start()有什么区别?

在 Java 中,run() 方法和 start() 方法在线程的使用中有重要区别:

run() 方法:

  • 当您直接调用线程对象的 run() 方法时,它会在当前线程中执行 run() 方法中的代码,不会启动新的线程。这就相当于普通的方法调用,不会实现多线程的并发执行效果。

start() 方法:

  • 调用线程对象的 start() 方法时,会启动一个新的线程,并在新线程中执行 run() 方法中的代码。
  • 这使得多个线程可以并发执行,从而实现多任务的同时处理,提高程序的执行效率和响应性。

总结:start() 方法中包含了run() 方法的使用,所以要实现线程的并发执行,应该调用 start() 方法,而不是直接调用 run() 方法。

代码展示

public class ThreadExample {
    public static void main(String[] args) {
        // 直接调用 run 方法,不会启动新线程
        MyThread thread1 = new MyThread();
        thread1.run();

        // 调用 start 方法,启动新线程执行 run 方法
        MyThread thread2 = new MyThread();
        thread2.start();
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("当前线程: " + Thread.currentThread().getName() + " 正在执行");
    }
}

在上述代码中,直接调用 thread1.run() 时,是在当前主线程中执行 run 方法的代码。而调用 thread2.start() 时,会启动一个新的线程来执行 run 方法中的代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值