Java多線程(一)Java多線程傳統實現方法

jopen 8年前發布 | 16K 次閱讀 Java開發

Java多線程(一)Java多線程傳統實現方法

Java多線程的傳統實現方法有兩種:一種是繼承Thread類并重寫其run方法;另一種是實現Runnable接口,實現其run方法。

/** * 多線程的傳統實現方法 * */
public class TraditionalThread {

    public static void main(String[] args) {

        /* * 方法1:覆蓋父類Thread的run方法 */
        Thread thread = new Thread() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("輸出1:" + Thread.currentThread().getName());
                    System.out.println("輸出2:" + this.getName());
                }
            }

        };
        thread.start();

        /* * 方法2:實現Runnable接口,實現其run方法 */
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("輸出1:" + Thread.currentThread().getName());
// System.out.println("輸出2:" + this.getName());
                }
            }

        });
        thread2.start();

        /* * 3:二者同時存在時的調用規則 * * 首先找子類的run方法, * 若子類沒有覆蓋run方法,則找Runnable的run方法(參考jdk中Thread.run()的實現) * 因此本代碼會執行子類覆蓋的run方法 */
        new Thread(new Runnable(){

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Runnable:" + Thread.currentThread().getName());
                }
            }

        }){

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread:" + Thread.currentThread().getName());
                }
            }

        }.start();
    }

}

來自: http://blog.csdn.net//kingzone_2008/article/details/44571181

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!