java的start()函数是什么意思_在Java中,start()函数在多线程中做了什么? - Break易站...

Java 多线程

在这两种方法中,我们都覆盖了run()函数,但是我们通过调用start()函数来启动一个线程。那么为什么我们不直接调用oveerridden run()函数呢?为什么总是调用start函数来执行一个线程?

调用start()函数时会发生什么?

调用函数时,将执行以下操作:

参数被评估。

新的堆栈帧被推入调用堆栈。

参数已初始化。

方法体被执行。

值被重新调整,当前堆栈帧从调用堆栈中弹出。

start()的目的是为线程创建一个单独的调用堆栈。它创建一个单独的调用堆栈,然后由JVM调用run()。

start()函数在Java多线程的示例

让我们看看如果我们不调用start()而是直接调用run()会发生什么。

// Java code to see that all threads are

// pushed on same stack if we use run()

// instead of start().

class ThreadTest extends Thread

{

public void run()

{

try

{

// Displaying the thread that is running

System.out.println ("Thread " +

Thread.currentThread().getId() +

" is running");

}

catch (Exception e)

{

// Throwing an exception

System.out.println ("Exception is caught");

}

}

}

// Main Class

public class Main

{

public static void main(String[] args)

{

int n = 8;

for (int i=0; i

{

ThreadTest object = new ThreadTest();

// start() is replaced with run() for

// seeing the purpose of start

object.run();

}

}

}

输出:

Thread 1 is running

Thread 1 is running

Thread 1 is running

Thread 1 is running

Thread 1 is running

Thread 1 is running

Thread 1 is running

Thread 1 is running

我们可以从上面的输出中看到,我们为所有线程获得了相同的ID,因为我们直接调用了run()。调用start()的程序会打印不同的ID.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值