Java 多线程基础(三) start() 和 run()

通过之前的学习可以看到,创建多线程过程中,最常用的便是 Thread 类中的 start() 方法和线程类的 run() 方法。两个方法都包含在 Thread 类中。

一、start() 方法和run() 方法的区别

Thread 类中包含了start() 方法,用于开启一个线程,调用该方法后,线程就进入就绪状态。

run() 方法和普通成员方法一样,可以重复调用。单独调用 run()方法时,会在当前线程执行 run() 方法,而不会启动新的线程。

二、start() 和 run() 的源码(基于JDK 1.8)

start() 方法的源码

public synchronized void start() {
// 如果线程不是"就绪状态",则抛出异常!
if (threadStatus != 0)
throw new IllegalThreadStateException();
// 将线程添加到ThreadGroup中
group.add(this);
boolean started = false;
try {
// start0() 启动线程
start0();
// 设置 started 标记
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) { }
}
}
private native void start0();

start()实际上是通过本地方法start0()启动线程的。而start0()会新运行一个线程,新线程会调用run()方法。

run() 方法的源码

private Runnable target;
public void run() {
  if (target != null) {
    target.run();
  }
}

target是一个Runnable对象。run()就是直接调用Thread线程的Runnable成员的run()方法,并不会新建一个线程。

三、实例

class MyThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
System.out.println(Thread.currentThread().getName() + " MyThread run()");
t1.run();
System.out.println(Thread.currentThread().getName() + " MyThread start()");
t1.start();
}
}

最新文章

  1. linux增加用户并赋予权限/用户和用户组操作命令
  2. myeclipse2013以及以后的最新版各种破解(其实就是获取活跃码而已)
  3. JVM 指令集
  4. python模块的安装
  5. MYSQL数据库主主同步实战
  6. 设计模式_Flyweight_享元模式
  7. Ubuntu Nginx 开机自启动
  8. python MySQLdb pymsql
  9. PHP $_POST 变量
  10. 大数据Hadoop——HDFS Shell操作
  11. Bytom信息上链教程
  12. Atitit 提升进度的大原则与方法  高层方法  attilax总结
  13. 【Kibana】Kibana入门教程
  14. JS security
  15. wcf的DataContractAttribute与DataMenmberAttribute
  16. ssh加密公私钥
  17. pselect 和 select
  18. exec和xargs
  19. sklearn的train_test_split
  20. bzoj 1189 [HNOI2007]紧急疏散evacuate 二分+网络流

热门文章

  1. python Lambda, filter, reduce and map
  2. Python--WebDriverWait+expected_conditions的一个应用
  3. 5.3 Go 匿名函数
  4. 4.1Go if-else
  5. SpringBoot瘦身
  6. 【JVM】GC 可达性分析中哪些算是GC ROOT?
  7. windows 10 2016 企业版 长期服务 激活方式
  8. [批处理教程之Shell]001.文本处理
  9. Java中的集合(十三) 实现Map接口的Hashtable
  10. Nuxt.js