程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java並發編程示例(十):線程組

Java並發編程示例(十):線程組

編輯:關於JAVA

Java並發編程示例(十):線程組。本站提示廣大學習愛好者:(Java並發編程示例(十):線程組)文章只能為提供參考,不一定能成為您想要的結果。以下是Java並發編程示例(十):線程組正文


對線程分組是Java並發API供給的一個風趣功效。我們可以將一組線程算作一個自力單位,而且可以隨便把持線程組中的線程對象。好比,可以掌握一組線程來運轉異樣的義務,無需關懷有若干線程還在運轉,還可使用一次中止挪用中止一切線程的履行。

Java供給了ThreadGroup類來掌握一個線程組。一個線程組可以經由過程線程對象來創立,也能夠由其他線程組來創立,生成一個樹形構造的線程。

依據《Effective Java》的解釋,不再建議應用ThreadGroup。建議應用Executor。

——D瓜哥特此解釋。

在本節,我們就應用ThreadGroup來開辟一個簡略的示例。我們將創立十個休眠時光不等的線程(好比模仿搜刮),當個中一個完成時,中止其他線程。

知其然

依照上面所示步調,完成示例代碼。

1.創立一個名為Result的類,用於存儲第一個完成義務的線程的名字。聲明一個String類型的公有變量,name,同時生成Setter/Getter辦法。代碼以下:


public class Result {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.創立一個名為SearchTask的類,並完成Runnable接口。代碼以下:


public class SearchTask implements Runnable {

3.聲明一個Result類型的公有變量,並經由過程結構函數來實例化該變量。代碼以下:


private Result result;

public SearchTask(Result result) {
    this.result = result;
}

4.完成run()辦法,在個中挪用doTask()辦法,來期待完成或被中止。該辦法還向掌握台打印信息來顯示線程的開端、停止或許中止。代碼以下:

@Override
public void run() {
    String name = Thread.currentThread().getName();
    System.out.printf("Thread %s: Start\n", name);
    try {
        doTask();
        result.setName(name);
    } catch (InterruptedException e) {
        System.out.printf("Thread %s: Interrupted\n", name);
        return;
    }
    System.out.printf("Thread %s: End\n", name);
}

5.完成doTask()辦法,該辦法將創立一個Random對象,然後應用該對象生成一個隨機數,來調理線程休眠的時光。代碼以下:

// 模仿搜刮
private void doTask() throws InterruptedException {
    Random random = new Random(new Date().getTime());
    int value = (int) (random.nextDouble() * 100);
    System.out.printf("Thread %s: %d\n",
            Thread.currentThread().getName(), value);
    TimeUnit.SECONDS.sleep(value);
}

6.創立示例法式的主類,Main,並完成main()辦法。代碼以下:

public class Main {
    public static void main(String[] args) {

7.創立一個稱號為Searcher的ThreadGroup對象。代碼以下:


ThreadGroup threadGroup = new ThreadGroup("Searcher");

8.然後,創立一個Result對象和SearchTask對象。代碼以下:

Result result = new Result();
SearchTask searchTask = new SearchTask(result);

9.SearchTask對象應用創立十個Thread對象,而且創立Thread對象時,將ThreadGroup對象作為第一個參數,傳遞給Thread類的結構函數。代碼以下:

for (int i = 0; i < 5; i++) {
    Thread thread = new Thread(threadGroup, searchTask);
    thread.start();
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

10.應用list()辦法將ThreadGroup對象的信息打印出來。代碼以下:


System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
System.out.println("Information about the Thread Group");
threadGroup.list();

11.應用activeCount()和enumerate()來獲得ThreadGroup對象中的活潑線程數並將其復制到一個線程數組中。應用get*()辦法,獲得線程的稱號和狀況。代碼以下:


Thread[] threads = new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads);
for (int i = 0; i < threadGroup.activeCount(); i++) {
    System.out.printf("Thread %s: %s\n", threads[i].getName(),
            threads[i].getState());
}

12.挪用waitFinish()辦法,期待ThreadGroup對象中的個中一個線程完成義務。稍後完成該辦法。代碼以下:

waitFinish(threadGroup);

13.應用interrupt()辦法,中止線程組中其他線程。代碼以下:


threadGroup.interrupt();

14.完成waitFinish()辦法,應用activeCount()辦法掌握線程的履行成果。代碼以下:


// 期待義務完成
private static void waitFinish(ThreadGroup threadGroup) {
    while (threadGroup.activeCount() > 9) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

15.運轉法式,檢查履行後果。

知其所以然

上面是法式履行的成果。你將看到list()辦法的輸入,各個線程的狀況等。

Thread Thread-0: Start
Thread Thread-0: 52
Thread Thread-1: Start
Thread Thread-1: 41
Thread Thread-2: Start
Thread Thread-2: 69
Thread Thread-3: Start
Thread Thread-3: 60
Thread Thread-4: Start
Thread Thread-4: 88
Number of Threads: 5
Information about the Thread Group
java.lang.ThreadGroup[name=Searcher,maxpri=10]
    Thread[Thread-0,5,Searcher]
    Thread[Thread-1,5,Searcher]
    Thread[Thread-2,5,Searcher]
    Thread[Thread-3,5,Searcher]
    Thread[Thread-4,5,Searcher]
Thread Thread-0: TIMED_WAITING
Thread Thread-1: TIMED_WAITING
Thread Thread-2: TIMED_WAITING
Thread Thread-3: TIMED_WAITING
Thread Thread-4: TIMED_WAITING
Thread Thread-1: Interrupted
Thread Thread-4: Interrupted
Thread Thread-2: Interrupted
Thread Thread-0: Interrupted
Thread Thread-3: Interrupted

ThreadGroup類保留著浩瀚Thread對象和聯系關系的ThreadGroup對象。可以經由過程挪用該類的辦法,拜訪線程的信息,還可以對其停止各類操作,好比中止等。

永無盡頭

ThreadGroup類還有很多多少辦法。請翻閱API文檔,檢查完全的辦法解釋。

拿來主義

本文是從 《Java 7 Concurrency Cookbook》 (D瓜哥竊譯為 《Java7並發示例集》 )翻譯而來,僅作為進修材料應用。沒有受權,不得用於任何貿易行動。

小有所成

上面是本節示例所用的代碼的完全版。

Result類的完全代碼:

package com.diguage.books.concurrencycookbook.chapter1.recipe10;

/**
 * 存儲查詢成果
 * Date: 2013-09-30
 * Time: 00:45
 */
public class Result {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

SearchTask類的完全代碼

package com.diguage.books.concurrencycookbook.chapter1.recipe10;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 模仿搜刮類
 * Date: 2013-10-02
 * Time: 22:38
 */
public class SearchTask implements Runnable {
    private Result result;

    public SearchTask(Result result) {
        this.result = result;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.printf("Thread %s: Start\n", name);
        try {
            doTask();
            result.setName(name);
        } catch (InterruptedException e) {
            System.out.printf("Thread %s: Interrupted\n", name);
            return;
        }
        System.out.printf("Thread %s: End\n", name);
    }

    // 模仿搜刮
    private void doTask() throws InterruptedException {
        Random random = new Random(new Date().getTime());
        int value = (int) (random.nextDouble() * 100);
        System.out.printf("Thread %s: %d\n",
                Thread.currentThread().getName(), value);
        TimeUnit.SECONDS.sleep(value);
    }
}

Main類的完全代碼:


package com.diguage.books.concurrencycookbook.chapter1.recipe10;

import java.util.concurrent.TimeUnit;

/**
 * 線程組示例主類
 * Date: 2013-10-02
 * Time: 22:45
 */
public class Main {
    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("Searcher");

        Result result = new Result();
        SearchTask searchTask = new SearchTask(result);

        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(threadGroup, searchTask);
            thread.start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.printf("Number of Threads: %d\n", threadGroup.activeCount());
        System.out.println("Information about the Thread Group");
        threadGroup.list();

        Thread[] threads = new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threads);
        for (int i = 0; i < threadGroup.activeCount(); i++) {
            System.out.printf("Thread %s: %s\n", threads[i].getName(),
                    threads[i].getState());
        }

        waitFinish(threadGroup);

        threadGroup.interrupt();
    }

    // 期待義務完成
    private static void waitFinish(ThreadGroup threadGroup) {
        while (threadGroup.activeCount() > 9) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved