天天看點

匿名内部類方式使用多線程

在開發中,為了友善使用線程,需要随手開線程,最簡單的做法就是采用匿名内部類方式使用多線程。

  匿名内部類的格式:

    new 類名或者接口名() {

      重寫方法;

    }

  本質:是該類的子類對象或者該接口的實作類對象。

    new Thread() {代碼...}.start();

    new Thread(new Runnable() {代碼...}) {}.start();

示例代碼如下:

1 package cn.itcast_11;
 2 
 3 /*
 4  * 匿名内部類的格式:
 5  *         new 類名或者接口名() {
 6  *             重寫方法;
 7  *         }
 8  * 
 9  *         本質:是該類的子類對象或者該接口的實作類對象。
10  */
11 public class ThreadDemo {
12     public static void main(String[] args) {
13         // 繼承Thread類來實作多線程
14         new Thread() {
15             @Override
16             public void run() {
17                 for (int x = 0; x < 100; x++) {
18                     System.out.println(Thread.currentThread().getName() + ":" + x);
19                 }
20             }
21         }.start();
22 
23         // 實作Runnable接口來實作多線程
24         new Thread(new Runnable() {
25             @Override
26             public void run() {
27                 for (int x = 0; x < 100; x++) {
28                     System.out.println(Thread.currentThread().getName() + ":" + x);
29                 }
30             }
31         }) {
32         }.start();
33 
34         // 面試題
35         // 到底執行的是Thread類的子類對象的run(),還是執行的是Runnable接口的實作類對象的run()呢? 答:是Thread類的子類對象的run() world
36         new Thread(new Runnable() {
37             @Override
38             public void run() {
39                 for (int x = 0; x < 100; x++) {
40                     System.out.println("hello" + ":" + x);
41                 }
42             }
43         }) {
44             @Override
45             public void run() {
46                 for (int x = 0; x < 100; x++) {
47                     System.out.println("world" + ":" + x);
48                 }
49             }
50         }.start();
51         
52     }
53 }      

我的GitHub位址:

https://github.com/heizemingjun

我的部落格園位址:

http://www.cnblogs.com/chenmingjun

我的螞蟻筆記部落格位址:

http://blog.leanote.com/chenmingjun

Copyright ©2018 黑澤明軍

【轉載文章務必保留出處和署名,謝謝!】