start和run方法的一些问题

1.认识start()和run()方法

start()

public void start()
使该线程开始执行;Java 虚拟机调用该线程的 run 方法。
结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。

多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。

抛出:
IllegalThreadStateException - 如果线程已经启动。
另请参见:
run(), stop()
run()
public void run()
如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。
Thread 的子类应该重写该方法。

指定者:
接口 Runnable 中的 run
另请参见:
start(), stop(), Thread(ThreadGroup, Runnable, String)

2. 区别:

可见真正能实现多线程的方式应该是调用start()方法而不是调用run方法。

只有调用了start()方法,才会表现出多线程的特性,不同线程的run()方法里面的代码交替执行。

如果只是调用run()方法,那么代码还是同步执行的,必须等待一个线程的run()方法里面的代码全部执行完毕之后,另外一个线程才可以执行其run()方法里面的代码。

3. 原理

为什么不能多次调用同一个线程的start()呢?抛出的异常是 java.lang.IllegalThreadStateException,非法的线程状态。

我们知道一个线程的启动过程简单来说是这样 start()--->start0(native方法)--->run()。这样真正实现了多线程的运行。如果直接执行run的话,只是一个普通方法,需要顺序执行,就是因为中间多了个start(native)方法。

这个方法我看不见,因为我看不懂cpp代码,只能通过调试了去看了。

Thread源码粗略分析:

1.  threadStatus是volatile的,并且初始值是0。

/* Java thread status for tools,
     * initialized to indicate thread 'not yet started'
     */

    private volatile int threadStatus = 0;
2. 

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
当执行到strat0()时,发现对于当前线程的threadStatus的值被随意改变成一个int型的变量,不在是0了,并且当此线程执行完毕之

后,这个值是2。无从得知为什么是2,这个代码我看不懂了~~~~~反正从java这边的源码可以看出,当执行start()方法时会去

判断threadStatus的值,如果不是初始值,就会抛出这个异常。这也是为什么不能重复调用start()的代码层面的原因。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值