Java7并發(fā)編程實(shí)戰(zhàn)手冊-1線程管理

1.線程的創(chuàng)建和運(yùn)行
通過實(shí)現(xiàn)Runnable接口創(chuàng)建線程

/**
 *  This class prints the multiplication table of a number
 */
public class Calculator implements Runnable {

    /**
     *  The number
     */
    private int number;
    
    /**
     *  Constructor of the class
     * @param number : The number
     */
    public Calculator(int number) {
        this.number=number;
    }
    
    /**
     *  Method that do the calculations
     */
    @Override
    public void run() {
        for (int i=1; i<=10; i++){
            System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
    }

}

/**
 *  Main class of the example
 */
public class Main {

    /**
     * Main method of the example
     * @param args
     */
    public static void main(String[] args) {

        //Launch 10 threads that make the operation with a different number
        for (int i=1; i<=10; i++){
            Calculator calculator=new Calculator(i);
            Thread thread=new Thread(calculator);
            thread.start();
        }
    }
}

2.線程信息的獲取和設(shè)置

/**
 * This class prints the multiplication table of a number
 *
 */
public class Calculator implements Runnable {

    /**
     *  The number
     */
    private int number;
    
    /**
     *  Constructor of the class
     * @param number : The number
     */
    public Calculator(int number) {
        this.number=number;
    }
    
    /**
     *  Method that do the calculations
     */
    @Override
    public void run() {
        for (int i=1; i<=10; i++){
            System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
    }

}
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.State;

import com.packtpub.java7.concurrency.chapter1.recipe2.task.Calculator;

/**
 *  Main class of the example
 */
public class Main {

    /**
     * Main method of the example
     * @param args
     */
    public static void main(String[] args) {

        // Thread priority infomation 
        System.out.printf("Minimum Priority: %s\n",Thread.MIN_PRIORITY);
        System.out.printf("Normal Priority: %s\n",Thread.NORM_PRIORITY);
        System.out.printf("Maximun Priority: %s\n",Thread.MAX_PRIORITY);
        
        Thread threads[];
        Thread.State status[];
        
        // Launch 10 threads to do the operation, 5 with the max
        // priority, 5 with the min
        threads=new Thread[10];
        status=new Thread.State[10];
        for (int i=0; i<10; i++){
            threads[i]=new Thread(new Calculator(i));
            if ((i%2)==0){
                threads[i].setPriority(Thread.MAX_PRIORITY);
            } else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("Thread "+i);
        }
        
        
        // Wait for the finalization of the threads. Meanwhile, 
        // write the status of those threads in a file
        try (FileWriter file = new FileWriter(".\\data\\log.txt");PrintWriter pw = new PrintWriter(file);){
            
            for (int i=0; i<10; i++){
                pw.println("Main : Status of Thread "+i+" : "+threads[i].getState());
                status[i]=threads[i].getState();
            }

            for (int i=0; i<10; i++){
                threads[i].start();  //啟動(dòng)后各個(gè)線程和Main線程競爭執(zhí)行機(jī)會(huì)
            }
            
            System.out.println("我是Main線程我在執(zhí)行");
            
            boolean finish=false;
            while (!finish) {
                System.out.println("進(jìn)入了while循環(huán)");
                for (int i=0; i<10; i++){
                    if (threads[i].getState()!=status[i]) {
                        System.out.println("記錄進(jìn)程狀態(tài):" + i);
                        writeThreadInfo(pw, threads[i],status[i]);
                        status[i]=threads[i].getState();
                    }
                }
                
                finish=true;
                for (int i=0; i<10; i++){
                    System.out.println("判斷是否中止:" + i);
                    finish=finish &&(threads[i].getState()==State.TERMINATED);
                }
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  This method writes the state of a thread in a file
     * @param pw : PrintWriter to write the data
     * @param thread : Thread whose information will be written
     * @param state : Old state of the thread
     */
    private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {
        pw.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());
        pw.printf("Main : Priority: %d\n",thread.getPriority());
        pw.printf("Main : Old State: %s\n",state);
        pw.printf("Main : New State: %s\n",thread.getState());
        pw.printf("Main : ************************************\n");
    }

}

附執(zhí)行結(jié)果

Minimum Priority: 1
Normal Priority: 5
Maximun Priority: 10
Thread 0: 0 * 1 = 0
Thread 6: 6 * 1 = 6
Thread 5: 5 * 1 = 5
Thread 5: 5 * 2 = 10
Thread 5: 5 * 3 = 15
Thread 5: 5 * 4 = 20
Thread 5: 5 * 5 = 25
Thread 5: 5 * 6 = 30
Thread 5: 5 * 7 = 35
Thread 5: 5 * 8 = 40
Thread 5: 5 * 9 = 45
Thread 5: 5 * 10 = 50
Thread 3: 3 * 1 = 3
Thread 3: 3 * 2 = 6
Thread 4: 4 * 1 = 4
Thread 1: 1 * 1 = 1
Thread 1: 1 * 2 = 2
Thread 1: 1 * 3 = 3
Thread 1: 1 * 4 = 4
Thread 1: 1 * 5 = 5
Thread 1: 1 * 6 = 6
Thread 1: 1 * 7 = 7
Thread 1: 1 * 8 = 8
Thread 1: 1 * 9 = 9
Thread 1: 1 * 10 = 10
Thread 2: 2 * 1 = 2
Thread 2: 2 * 2 = 4
Thread 4: 4 * 2 = 8
Thread 4: 4 * 3 = 12
Thread 4: 4 * 4 = 16
Thread 3: 3 * 3 = 9
Thread 3: 3 * 4 = 12
Thread 3: 3 * 5 = 15
Thread 9: 9 * 1 = 9
Thread 9: 9 * 2 = 18
Thread 9: 9 * 3 = 27
Thread 9: 9 * 4 = 36
Thread 9: 9 * 5 = 45
Thread 9: 9 * 6 = 54
Thread 9: 9 * 7 = 63
Thread 9: 9 * 8 = 72
Thread 8: 8 * 1 = 8
Thread 8: 8 * 2 = 16
Thread 8: 8 * 3 = 24
Thread 8: 8 * 4 = 32
Thread 7: 7 * 1 = 7
Thread 7: 7 * 2 = 14
Thread 7: 7 * 3 = 21
Thread 7: 7 * 4 = 28
Thread 7: 7 * 5 = 35
Thread 7: 7 * 6 = 42
Thread 7: 7 * 7 = 49
Thread 6: 6 * 2 = 12
Thread 6: 6 * 3 = 18
Thread 6: 6 * 4 = 24
Thread 6: 6 * 5 = 30
Thread 6: 6 * 6 = 36
Thread 6: 6 * 7 = 42
Thread 6: 6 * 8 = 48
Thread 6: 6 * 9 = 54
Thread 6: 6 * 10 = 60
我是Main線程我在執(zhí)行
Thread 0: 0 * 2 = 0
Thread 0: 0 * 3 = 0
Thread 0: 0 * 4 = 0
Thread 0: 0 * 5 = 0
Thread 0: 0 * 6 = 0
Thread 0: 0 * 7 = 0
Thread 0: 0 * 8 = 0
進(jìn)入了while循環(huán)
Thread 7: 7 * 8 = 56
Thread 7: 7 * 9 = 63
Thread 7: 7 * 10 = 70
Thread 8: 8 * 5 = 40
Thread 9: 9 * 9 = 81
Thread 9: 9 * 10 = 90
Thread 3: 3 * 6 = 18
Thread 4: 4 * 5 = 20
Thread 4: 4 * 6 = 24
Thread 4: 4 * 7 = 28
Thread 4: 4 * 8 = 32
Thread 4: 4 * 9 = 36
Thread 4: 4 * 10 = 40
Thread 2: 2 * 3 = 6
Thread 2: 2 * 4 = 8
Thread 2: 2 * 5 = 10
Thread 2: 2 * 6 = 12
Thread 2: 2 * 7 = 14
Thread 2: 2 * 8 = 16
Thread 2: 2 * 9 = 18
Thread 3: 3 * 7 = 21
Thread 3: 3 * 8 = 24
Thread 3: 3 * 9 = 27
Thread 3: 3 * 10 = 30
Thread 8: 8 * 6 = 48
Thread 8: 8 * 7 = 56
記錄進(jìn)程狀態(tài):0
Thread 0: 0 * 9 = 0
Thread 0: 0 * 10 = 0
Thread 8: 8 * 8 = 64
Thread 8: 8 * 9 = 72
Thread 8: 8 * 10 = 80
Thread 2: 2 * 10 = 20
記錄進(jìn)程狀態(tài):1
記錄進(jìn)程狀態(tài):2
記錄進(jìn)程狀態(tài):3
記錄進(jìn)程狀態(tài):4
記錄進(jìn)程狀態(tài):5
記錄進(jìn)程狀態(tài):6
記錄進(jìn)程狀態(tài):7
記錄進(jìn)程狀態(tài):8
記錄進(jìn)程狀態(tài):9
判斷是否中止:0
判斷是否中止:1
判斷是否中止:2
判斷是否中止:3
判斷是否中止:4
判斷是否中止:5
判斷是否中止:6
判斷是否中止:7
判斷是否中止:8
判斷是否中止:9

3.線程中斷
判斷一個(gè)數(shù)是否是素?cái)?shù)/質(zhì)數(shù),從1開始打印素?cái)?shù)碘耳,持續(xù)5秒后中斷

import java.util.concurrent.TimeUnit;
/**
 *  Main class of the sample. Launch the PrimeGenerator, waits 
 *  five seconds and interrupts the Thread
 */
public class Main {

    /**
     * Main method of the sample. Launch the PrimeGenerator, waits
     * five seconds and interrupts the Thread
     * @param args
     */
    public static void main(String[] args) {

        // Launch the prime numbers generator
        Thread task=new PrimeGenerator();
        task.start();
        
        // Wait 5 seconds
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // Interrupt the prime number generator
        task.interrupt();
    }

}
/**
 *  This class generates prime numbers until is interrumped
 */
public class PrimeGenerator extends Thread{

    /**
     *  Central method of the class
     */
    @Override
    public void run() {
        long number=1L;
        
        // This bucle never ends... until is interrupted
        while (true) {
            if (isPrime(number)) {
                System.out.printf("Number %d is Prime\n",number);
            }
            
            // When is interrupted, write a message and ends
            if (isInterrupted()) {
                System.out.printf("The Prime Generator has been Interrupted\n");
                return;
            }
            number++;
        }
    }

    /**
     *  Method that calculate if a number is prime or not
     * @param number : The number
     * @return A boolean value. True if the number is prime, false if not.
     */
    private boolean isPrime(long number) {
        if (number <=2) {
            return true;
        }
        for (long i=2; i<number; i++){
            if ((number % i)==0) {
                return false;
            }
        }
        return true;
    }

}

4.線程中斷的控制

import java.io.File;

/**
 * This class search for files with a name in a directory
 */
public class FileSearch implements Runnable {

    /**
     * Initial path for the search
     */
    private String initPath;   //初始路徑
    /**
     * Name of the file we are searching for
     */
    private String fileName;   //文件名稱

    /**
     * Constructor of the class
     * 
     * @param initPath
     *            : Initial path for the search
     * @param fileName
     *            : Name of the file we are searching for
     */
    public FileSearch(String initPath, String fileName) {
        this.initPath = initPath;
        this.fileName = fileName;
    }

    /**
     * Main method of the class
     */
    @Override
    public void run() {
        File file = new File(initPath);
        if (file.isDirectory()) {
            try {
                directoryProcess(file);
            } catch (InterruptedException e) {
                System.out.printf("%s: The search has been interrupted",Thread.currentThread().getName());
                cleanResources();
            }
        }
    }

    /**
     * Method for cleaning the resources. In this case, is empty
     */
    private void cleanResources() {

    }

    /**
     * Method that process a directory
     * 
     * @param file
     *            : Directory to process
     * @throws InterruptedException
     *             : If the thread is interrupted
     */
    private void directoryProcess(File file) throws InterruptedException {

        // Get the content of the directory  遍歷目錄下的所有文件和文件夾
        File list[] = file.listFiles();
        if (list != null) {
            for (int i = 0; i < list.length; i++) {
                if (list[i].isDirectory()) {
                    // If is a directory, process it
                    directoryProcess(list[i]);  //如果是文件夾則遞歸調(diào)用該方法
                } else {
                    // If is a file, process it
                    fileProcess(list[i]);  //如果是文件則調(diào)用fileProcess方法
                }
            }
        }
        // Check the interruption  //處理完所有文件和文件夾后檢查是否線程中斷
        if (Thread.interrupted()) {  //靜態(tài)方法辛辨,可以設(shè)置interrupted屬性為false
            throw new InterruptedException();
        }
    }

    /**
     * Method that process a File
     * 
     * @param file
     *            : File to process
     * @throws InterruptedException
     *             : If the thread is interrupted
     */
    private void fileProcess(File file) throws InterruptedException {
        // Check the name  比較當(dāng)前文件的文件名和要查找的文件名
        if (file.getName().equals(fileName)) {
            System.out.printf("%s : %s\n",Thread.currentThread().getName() ,file.getAbsolutePath());
        }

        // Check the interruption //做完比較后檢查是否線程中斷
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }

}

import java.util.concurrent.TimeUnit;
/**
 *  Main class of the example. Search for the autoexect.bat file
 *  on the Windows root folder and its subfolders during ten seconds
 *  and then, interrupts the Thread
 */
public class Main {

    /**
     * Main method of the core. Search for the autoexect.bat file
     * on the Windows root folder and its subfolders during ten seconds
     * and then, interrupts the Thread
     * @param args
     */
    public static void main(String[] args) {
        // Creates the Runnable object and the Thread to run it
        FileSearch searcher=new FileSearch("C:\\","autoexec.bat");
        Thread thread=new Thread(searcher);
        
        // Starts the Thread
        thread.start();
        
        // Wait for ten seconds  等待10秒中斷線程
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        // Interrupts the thread
        thread.interrupt();
    }

}

5.線程的休眠與恢復(fù)

6.等待線程的終止

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末斗搞,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子僻焚,更是在濱河造成了極大的恐慌,老刑警劉巖虑啤,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異狞山,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)萍启,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來局服,“玉大人,你說我怎么就攤上這事淫奔。” “怎么了搏讶?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵霍殴,是天一觀的道長媒惕。 經(jīng)常有香客問我来庭,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任肴盏,我火速辦了婚禮,結(jié)果婚禮上菜皂,老公的妹妹穿的比我還像新娘。我一直安慰自己恍飘,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布母蛛。 她就那樣靜靜地躺著,像睡著了一般彩郊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上秫逝,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天询枚,我揣著相機(jī)與錄音筷登,去河邊找鬼哩盲。 笑死狈醉,一個(gè)胖子當(dāng)著我的面吹牛廉油,可吹牛的內(nèi)容都是我干的苗傅。 我是一名探鬼主播抒线,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼渣慕,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了逊桦?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤睡陪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后兰迫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體信殊,經(jīng)...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡汁果,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鳄乏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡汞窗,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出仲吏,到底是詐尸還是另有隱情,我是刑警寧澤裹唆,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布只洒,位于F島的核電站许帐,受9級特大地震影響毕谴,放射性物質(zhì)發(fā)生泄漏成畦。R本人自食惡果不足惜涝开,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望舀武。 院中可真熱鬧,春花似錦银舱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽诚欠。三九已至宪祥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蝗羊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工耀找, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留业崖,地道東北人野芒。 一個(gè)月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓双炕,卻偏偏與公主長得像,于是被迫代替她去往敵國和親妇斤。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,093評論 25 707
  • 剛剛給媽媽打電話被狠狠數(shù)落了一頓荸恕,她心里不舒服,我也不舒服死相。 我是獨(dú)女,婆婆家是農(nóng)村的算撮,老人不肯來我這住著...
    青藤花鬧閱讀 354評論 0 1
  • 在前端領(lǐng)域,框架一般分兩種: 界面框架和 代碼框架 界面框架:Bootstrap肮柜、Foundation、Seman...
    呼呼呼lys閱讀 75評論 0 3
  • 卡之家游戲播報(bào):LOL最新英雄翠神艾翁的超神攻略!想必大神們都聽說了新英雄翠神艾翁狸驳,畢竟是一個(gè)新英雄,大神們肯定是...
    卡之家閱讀 369評論 0 0
  • 總會(huì)有幾天不想理會(huì)身邊的一切 想屏蔽所有 總用各種理由搪塞朋友的消息耙箍、電話 會(huì)想到自己是不是活膩了 對于生活沒有了...
    Chiang閱讀 153評論 0 0