Java7并发编程实战手册-1线程管理

1.线程的创建和运行
通过实现Runnable接口创建线程

/**
 *  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.线程信息的获取和设置

/**
 * 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();  //启动后各个线程和Main线程竞争执行机会
            }
            
            System.out.println("我是Main线程我在执行");
            
            boolean finish=false;
            while (!finish) {
                System.out.println("进入了while循环");
                for (int i=0; i<10; i++){
                    if (threads[i].getState()!=status[i]) {
                        System.out.println("记录进程状态:" + 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");
    }

}

附执行结果

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线程我在执行
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
进入了while循环
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
记录进程状态: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
记录进程状态:1
记录进程状态:2
记录进程状态:3
记录进程状态:4
记录进程状态:5
记录进程状态:6
记录进程状态:7
记录进程状态:8
记录进程状态:9
判断是否中止:0
判断是否中止:1
判断是否中止:2
判断是否中止:3
判断是否中止:4
判断是否中止:5
判断是否中止:6
判断是否中止:7
判断是否中止:8
判断是否中止:9

3.线程中断
判断一个数是否是素数/质数,从1开始打印素数,持续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]);  //如果是文件夹则递归调用该方法
                } else {
                    // If is a file, process it
                    fileProcess(list[i]);  //如果是文件则调用fileProcess方法
                }
            }
        }
        // Check the interruption  //处理完所有文件和文件夹后检查是否线程中断
        if (Thread.interrupted()) {  //静态方法,可以设置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  比较当前文件的文件名和要查找的文件名
        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.线程的休眠与恢复

6.等待线程的终止

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,240评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,328评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,182评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,121评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,135评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,093评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,013评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,854评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,295评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,513评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,678评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,398评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,989评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,636评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,801评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,657评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,558评论 2 352

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,062评论 25 707
  • 刚刚给妈妈打电话被狠狠数落了一顿,她心里不舒服,我也不舒服。 我是独女,婆婆家是农村的,老人不肯来我这住着...
    青藤花闹阅读 354评论 0 1
  • 在前端领域,框架一般分两种: 界面框架和 代码框架 界面框架:Bootstrap、Foundation、Seman...
    呼呼呼lys阅读 75评论 0 3
  • 卡之家游戏播报:LOL最新英雄翠神艾翁的超神攻略!想必大神们都听说了新英雄翠神艾翁,毕竟是一个新英雄,大神们肯定是...
    卡之家阅读 369评论 0 0
  • 总会有几天不想理会身边的一切 想屏蔽所有 总用各种理由搪塞朋友的消息、电话 会想到自己是不是活腻了 对于生活没有了...
    Chiang阅读 153评论 0 0