thread.start java_Java Thread start()方法

Thread类的start()方法用于开始执行线程。 此方法的结果是执行两个并发运行的线程:当前线程(从调用start方法返回)和另一个线程(执行其run方法)。

start()方法在内部调用Runnable接口的run()方法,以在单独的线程中执行run()方法中指定的代码。

启动线程执行以下任务:

它统计一个新线程

线程从初始状态移动到可运行状态。

当线程有机会执行时,它的目标run()方法将运行。

语法

public void start()

返回值

此方法没有返回值。

异常

IllegalThreadStateException – 如果多次调用start()方法,则抛出此异常。

示例1: 通过扩展Thread类

public class StartExp1 extends Thread { public void run() { System.out.println("Thread is running..."); } public static void main(String args[]) { StartExp1 t1=new StartExp1(); // this will call run() method t1.start(); } }

执行上面示例代码,得到以下结果:

Thread is running...

示例2: 通过实现Runnable接口

public class StartExp2 implements Runnable { public void run() { System.out.println("Thread is running..."); } public static void main(String args[]) { StartExp2 m1=new StartExp2 (); Thread t1 =new Thread(m1); // this will call run() method t1.start(); } }

执行上面示例代码,得到以下结果:

Thread is running...

示例3: 多次调用start()方法时

public class StartExp3 extends Thread { public void run() { System.out.println("First thread running..."); } public static void main(String args[]) { StartExp3 t1=new StartExp3(); t1.start(); // It will through an exception because you are calling start() method more than one time t1.start(); } }

执行上面示例代码,得到以下结果:

First thread running... Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:708) at StartExp3.main(StartExp3.java:12)

¥ 我要打赏 纠错/补充 收藏

哥,这回真没有了

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值