首頁 >Java >java教程 >Java並發之線程的使用以及建立啟動線程

Java並發之線程的使用以及建立啟動線程

黄舟
黄舟原創
2017-09-30 10:38:541534瀏覽


建立線程

Thread說明

  • #線程是程式中的執行線程,java虛擬機器允許應用程式並發的運行多個線程。

  • 每個執行緒都有一個優先權,高優先權執行緒的執行優先於低優先權執行緒。每個線程都可以或不可以標記為一個守護程序。當某個執行緒中執行的程式碼建立一個新Thread 物件時,該新執行緒的初始優先權被設定為建立執行緒的優先權,並且當且僅當建立執行緒是守護執行緒時,新執行緒才是守護程序。

  • 當 Java 虛擬機啟動時,通常都會有單一非守護執行緒(它通常會呼叫某個指定類別的 main 方法)。 Java 虛擬機會繼續執行線程,直到下列任一情況出現時為止:  
    #            1.地呼叫了 Runtime 類別的 exit 方法,且安全管理器允許退出作業發生。  
               2.非守護執行緒的所有執行緒都已停止運行,無論是透過從對 run 方法的呼叫中返回,或是透過拋出一個傳播到 run 方法之外的例外。

  • 實作執行緒的方式,會在後續的章節中介紹

#原始碼參考如下:

/**
 * A <i>thread</i> is a thread of execution in a program. The Java
 * Virtual Machine allows an application to have multiple threads of
 * execution running concurrently.
 * <p>
 * Every thread has a priority. Threads with higher priority are
 * executed in preference to threads with lower priority. Each thread
 * may or may not also be marked as a daemon. When code running in
 * some thread creates a new <code>Thread</code> object, the new
 * thread has its priority initially set equal to the priority of the
 * creating thread, and is a daemon thread if and only if the
 * creating thread is a daemon.
 * <p>
 * When a Java Virtual Machine starts up, there is usually a single
 * non-daemon thread (which typically calls the method named
 * <code>main</code> of some designated class). The Java Virtual
 * Machine continues to execute threads until either of the following
 * occurs:
 * <ul>
 * <li>The <code>exit</code> method of class <code>Runtime</code> has been
 *     called and the security manager has permitted the exit operation
 *     to take place.
 * <li>All threads that are not daemon threads have died, either by
 *     returning from the call to the <code>run</code> method or by
 *     throwing an exception that propagates beyond the <code>run</code>
 *     method.
 * </ul>
 * <p>
 * There are two ways to create a new thread of execution. One is to
 * declare a class to be a subclass of <code>Thread</code>. This
 * subclass should override the <code>run</code> method of class
 * <code>Thread</code>. An instance of the subclass can then be
 * allocated and started. For example, a thread that computes primes
 * larger than a stated value could be written as follows:
 * <hr><blockquote><pre class="brush:php;toolbar:false">
 *     class PrimeThread extends Thread {
 *         long minPrime;
 *         PrimeThread(long minPrime) {
 *             this.minPrime = minPrime;
 *         }
 *
 *         public void run() {
 *             // compute primes larger than minPrime
 *              . . .
 *         }
 *     }
 * 

 * 

 * The following code would then create a thread and start it running:  * 

 *     PrimeThread p = new PrimeThread(143);
 *     p.start();
 * 
 * 

 * The other way to create a thread is to declare a class that  * implements the Runnable interface. That class then  * implements the run method. An instance of the class can  * then be allocated, passed as an argument when creating  * Thread, and started. The same example in this other  * style looks like the following:  * 


 *     class PrimeRun implements Runnable {
 *         long minPrime;
 *         PrimeRun(long minPrime) {
 *             this.minPrime = minPrime;
 *         }
 *
 *         public void run() {
 *             // compute primes larger than minPrime
 *              . . .
 *         }
 *     }
 * 

 * 

 * The following code would then create a thread and start it running:  * 

 *     PrimeRun p = new PrimeRun(143);
 *     new Thread(p).start();
 * 
 * 

 * Every thread has a name for identification purposes. More than  * one thread may have the same name. If a name is not specified when  * a thread is created, a new name is generated for it.  * 

 * Unless otherwise noted, passing a {@code null} argument to a constructor  * or method in this class will cause a {@link NullPointerException} to be  * thrown.  *  * @author  unascribed  * @see     Runnable  * @see     Runtime#exit(int)  * @see     #run()  * @see     #stop()  * @since   JDK1.0  */ publicclass Thread implements Runnable {

所需的資訊

       在執行執行緒之前先建構一個執行緒對象,執行緒物件在建構的時候需要提供執行緒所需要的屬性,如執行緒所屬的執行緒群組、執行緒優先權、是否是Daemon執行緒等資訊。在new Thread時會呼叫以下方法進行實例化Thread物件。
初始化程式碼如下:

    /**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if null
     */
    private void init(ThreadGroup g, Runnable target, String name,                      
    long stackSize, AccessControlContext acc) {        
    if (name == null) {            
    throw new NullPointerException("name cannot be null");
        }        
        this.name = name;        //当前线程作为该线程的父线程
        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();        //线程组的获取:如果传入的参数为空首先获取系统默认的安全组,如果为空获取父线程的安全组
        if (g == null) {            
        /* Determine if it&#39;s an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }            /* If the security doesn&#39;t have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();        /*
         * Do we have the required permissions?
         */
        if (security != null) {            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();        
        this.group = g;        //设置daemon 、priority 属性为父线程对应的值
        this.daemon = parent.isDaemon();        
        this.priority = parent.getPriority();        
        
        if (security == null || isCCLOverridden(parent.getClass()))            
        this.contextClassLoader = parent.getContextClassLoader();        
        else
            this.contextClassLoader = parent.contextClassLoader;        
            this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();        
                this.target = target;
        setPriority(priority);        //将父线程的InheritableThreadLocal复制过来
        if (parent.inheritableThreadLocals != null)            
        this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);        
                /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;        /* Set thread ID */ 
        //生成线程id(一个long型的字段threadSeqNumber)
        tid = nextThreadID();
    }

結論

        一個新建的Thread物件(new Thread()),是由其父執行緒(目前執行緒)進行空間分配,而子執行緒繼承了父執行緒的Daemon、優先權和載入資源的contextClassLoader,以及可繼承的ThreadLocal,同時會為子執行緒指派一個執行緒id。一個可以運行的線程物件完成初始化工作,並且在堆記憶體中等待運行。

建構的方式

繼承Thread

程式碼

//方法1通过继承Thread实现class MyThread extends Thread{

    //需要实现的方法,该方法执行具体的业务逻辑
    @Override    public void run() {
        System.out.println(Thread.currentThread().getName()
                +" @@@@ MyThread。run()我是通过继承Thread实现的多线程");
    }

}

說明

      透過Thread原始碼發現(Thread implements Runnable)發現thread其實也是實作了runnable介面的一個實例,它代表一個執行緒的實例,並且,啟動執行緒的唯一方法就是透過Thread類別的start()實例方法。 start()方法是一個native方法,它將啟動一個新線程,並執行run()方法。這種方式實作多執行緒很簡單,透過自己的類別直接extend Thread,並複寫run()方法,就可以啟動新執行緒並執行自己定義的run()方法。

      其中run()方法的方法體代表了執行緒需要完成的任務,稱為執行緒執行體。當創建此線程類別物件時一個新的線程得以創建,並進入到線程新建狀態。透過呼叫線程物件所引用的start()方法,使得該線程進入到就緒狀態,此時此線程並不一定會馬上得以執行,這取決於CPU調度時機。

實作介面Runnable

程式碼

//方法2通过实现runnable接口
//实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,
//并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。class MyRunnable implements Runnable{

    @Override    public void run() {
        System.out.println(Thread.currentThread().getName()+                
        " @@@@ MyRunnable。run()我是通过实现Runnable接口实现的多线程");
    }

}

使用Callable、Future實作有傳回結果的多執行緒

      使用Callable和Future介面建立執行緒。具體是建立Callable介面的實作類,並實作clall()方法。並使用FutureTask類別來包裝Callable實作類別的對象,並以此FutureTask物件作為Thread對象的target來建立執行緒。
      可返回值的任務必須實現Callable接口,類似的,無返回值的任務必須Runnable接口。執行Callable任務後,可以取得一個Future的對象,在該對像上調用get就可以獲取到Callable任務返回的Object了,再結合線程池接口ExecutorService就可以實現傳說中有返回結果的多線程了(關於Executor的使用後續的文章中詳細介紹。)。

//方法3通过Executor框架实现class MyCallable implements Callable<Integer>{
    //需要实现call方法而不是run方法
    @Override    public Integer call() throws Exception {        return 100;
    }
}

啟動執行緒

透過原始碼分析得出:

  • #1.物件初始化完成之後,透過執行start方法來執行這個線程,並且java虛擬機會調用該線程的run方法執行線程的業務邏輯;

  • 2.調用start方法之後發現會同時有兩個線程在執行:當前線程(parent執行緒【同步告知java虛擬機,只要執行緒規劃器空閒,應立即啟動呼叫start方法的執行緒】,從呼叫返回給start方法)和另一個執行緒(執行其run方法)。

  • 3.並且多次啟動一個執行緒是非法的。特別是當執行緒已經結束執行後,不能再重新啟動。

    start方法原始碼說明如下:

   /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    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&#39;s list of threads
         * and the group&#39;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();

参考代码

public class TestCreateThread {    public static void main(String[] args) {
        Thread myThread = new MyThread();
        myThread.setName("myThread");
        myThread.start();

        Runnable myRunnable = new MyRunnable();
        Thread myRunnableThread = new Thread(myRunnable);
        myRunnableThread.setName("myRunnableThread");
        myRunnableThread.start();

        Thread myRunnableThread2 = new MyThread(myRunnable);
        myRunnableThread2.setName("myRunnableThread2");
        myRunnableThread2.start();        //执行结果参考如下:
        //myThread @@@@ MyThread。run()我是通过继承Thread实现的多线程
        //myRunnableThread2 @@@@ MyThread。run()我是通过继承Thread实现的多线程
        //myRunnableThread @@@@ MyRunnable。run()我是通过实现Runnable接口实现的多线程

        //测试callable方法
        // 创建MyCallable对象
        Callable<Integer> myCallable = new MyCallable();    
        //使用FutureTask来包装MyCallable对象
        FutureTask<Integer> ft = new FutureTask<Integer>(myCallable); 
        //FutureTask对象作为Thread对象的target创建新的线程
        Thread thread = new Thread(ft);
        thread.start();//启用

        //获取信息
        try {            //取得新创建的新线程中的call()方法返回的结果
            //当子线程此方法还未执行完毕,ft.get()方法会一直阻塞,
            //直到call()方法执行完毕才能取到返回值。
            int sum = ft.get();
            System.out.println("sum = " + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }        //使用ExecutorService处理多线程
        ExecutorService pool = Executors.newFixedThreadPool(10);  
        Future<Integer> f = pool.submit(myCallable);  
        // 关闭线程池  
        pool.shutdown(); 
        try {            int sum1 = f.get();
            System.out.println("sum1 = " + sum1);
        } catch (InterruptedException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

启动线程的注意事项


Java並發之線程的使用以及建立啟動線程


      无论何种方式,启动一个线程,就要给它一个名字!这对排错诊断系统监控有帮助。否则诊断问题时,无法直观知道某个线程的用途。

Thread与Runnable的关系

实现关系

Thread实现接口Runnable,并且实现了run方法,代码参考如下:

        //如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;
        //否则,该方法不执行任何操作并返回。
        //Thread 的子类应该重写该方法。
        /**
         * If this thread was constructed using a separate
         * <code>Runnable</code> run object, then that
         * <code>Runnable</code> object&#39;s <code>run</code> method is called;
         * otherwise, this method does nothing and returns.
         * <p>
         * Subclasses of <code>Thread</code> should override this method.
         *
         * @see     #start()
         * @see     #stop()
         * @see     #Thread(ThreadGroup, Runnable, String)
         */
        @Override
        public void run() {            if (target != null) {
                target.run();
            }
        }

}

区别

      当执行到Thread类中的run()方法时,会首先判断target是否存在,存在则执行target中的run()方法,也就是实现了Runnable接口并重写了run()方法的类中的run()方法。当时如果该Runnable的子类是通过一个继承Thread的子类(该且重写了run方法),则真正执行的是Thread子类重写的run方法(由于多态的原因)。

以上是Java並發之線程的使用以及建立啟動線程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn