美文网首页java基础
java多线程源码解读 start,run,join,yied

java多线程源码解读 start,run,join,yied

作者: _npc_ | 来源:发表于2017-04-16 13:48 被阅读40次

java
/**

  • Created by 陈奇 on 2017/4/14 0014.
    */
    public class ThreadHelloWord implements Runnable {
    @Override
    public void run() {
    System.out.println("hello word");
    }

    public static void main(String[] args) {
    ThreadHelloWord t = new ThreadHelloWord();
    Thread th = new Thread(t);
    System.out.println("states="+th.getState());
    th.start();
    System.out.println(th.getName());
    System.out.println("states="+th.getState());

    }
    }

* 这一段代码创建了一个线程,并打印出hello Word,
先看一下runnable接口源码吧.
```java```
/* @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
} ```
*  Runnable自jdk1.0定义,只定义了一个run方法。实现接口必须实现其方法,所以重写了run方法。
在看下Thread类
```java```
public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
  • Thread类实现了runnable接口,并获取寄存器,也就是说每一个线程都有一个寄存器,再看下star()方法
    java
    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 */
          }
      }
    

    }
    private native void start0(); //本地方法执行线程

这里有一个小疑问,既然线程有自己独立的寄存器为什么还要加锁呢?

yield()方法让出执行权
 ```java```
  public static native void yield(); //本地方法
package com.cn.threadpool;

/**
 * Created by 陈奇 on 2017/4/14 0014.
 */
public class ThreadHelloWord extends Thread {
    private String helloword;
    ThreadHelloWord(){}
    ThreadHelloWord(String helloword){
       super(helloword);
    }
    @Override
    public void run() {
        for (int i = 0; i <20 ; i++) {
            System.out.println("" + this.getName() + "-----" + i);
            // 当i为10时,该线程就会把CPU时间让掉,让其他或者自己的线程执行(也就是谁先抢到谁执行)
            if (i == 10) {
                this.yield();
            }
        }
    }

    public static void main(String[] args) {
        ThreadHelloWord h = new ThreadHelloWord("h");
        ThreadHelloWord w = new ThreadHelloWord("w");
        Thread th = new Thread(h);
        Thread tw = new Thread(w);
        th.start();
        tw.start();

    }
}
Paste_Image.png Paste_Image.png

join() 方法
源码
java
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (millis == 0) {
        while (isAlive()) {
            wait(0);
        }
    } else {
        while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay);          // 调用wait方法
            now = System.currentTimeMillis() - base;
        }
    }
}
join方法调用的是object的wait方法,
demo
  ```java```
/**
 * Created by 陈奇 on 2017/4/16 0016.
 */
public class JoinTest extends Thread {
    JoinTest(String name){
        super(name);
    }
    @Override
    public void run() {
        try {
            sleep(30);
            System.out.println(this.getName()+"____run ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new JoinTest("t"));
        Thread t1 = new Thread(new JoinTest("t1"));
        t.start();                                          // wait(0),立即执行
        t.join();
        t1.start();

        t1.join(10); //main线程等待时间
        System.out.println("main end");
    }
}
Paste_Image.png

相关文章

  • java多线程源码解读 start,run,join,yied

    java/** Created by 陈奇 on 2017/4/14 0014.*/public class Th...

  • Java-3

    线程中的join()多线程中的run()和start()java中的++i操作是线程安全的吗3*0.1 == 0....

  • Java多线程中start()和run()的区别

    Java多线程中start()和run()的区别 Java的线程是通过java.lang.Thread类来实现的。...

  • Java线程的5种状态及切换

    Java线程的5种状态及切换 thread的run 和start的区别:多线程-Thread的run()与star...

  • 线程

    1.start和run方法 :run方法只在主线程实现,无法实现多线程。start开启多线程 2.开启线程...

  • java多线程

    java多线程 线程类源码解读(2)-线程状态及常用方法 线程类源码解读(3)-线程中断 逐行分析AQS源码(1)...

  • Java多线程与常遇面试题总结

    Java多线程面试问题总结 1、多线程有什么用? 2、创建线程的方式 3、start()方法和run()方法的区别...

  • Java Thread 的 run() 与 start() 的区

    1. start 和 run 方法解释: 1) start:用start方法来启动线程,真正实现了多线程运行,这时...

  • python多线程

    run():用以表示线程活动的方法。 start():启动线程活动。 join([time]):等待至线程中止。这...

  • Java Thread 知识点

    一、Thread的start() 及 run() start()方法来启动线程,真正实现了多线程运行,这时无需等待...

网友评论

    本文标题:java多线程源码解读 start,run,join,yied

    本文链接:https://www.haomeiwen.com/subject/mgaiittx.html