Java并发编程之线程管理(上)

1线程管理

    在这一节中,我们将学习如何创建和运行一个线程。在Java语言中,我们有两种方式创建一个线程:

1.       扩展Thread类,覆盖run()方法

2.       构建一个实现Runnable接口的类,定义自己run()方法,然后,实用则个类的实例对象作为Thread构造方法的参数来创建Thread对象。

创建一个线程对象,它不会创建一个新的执行线程。也就是说,调用一个实现了Runnable接口的类的run()方法,它不会创建一个新的执行线程。仅仅是调用start()方法时,一个新的线程才会被创建。

Thread类保存了一些能够帮助我们标示一个线程的属性信息。

1.       ID: 每个线程独一无二的标识符。

2.       Name: 存储线程的名称。

3.       Priority: 线程对象的优先级属性,其值范围是0到10.除非有特殊要求,一般不推荐修改线程的优先级属性。

4.       Status: 这个属性表示线程当前的状态,在Java中,有六种状态:new、runnable

Blocked、time waiting和terminated。

创建一个简单的线程程序。

 

public class Worker implements Runnable{
 
    private intnumber;
   
    /**
     * Constructor of the class
     * @param number : The number
     */
    public Worker(intnumber) {
        this.number=number;
    }
    /**
     * Method that do the calculations
     */
    @Override
    public voidrun() {
        for (int i=1; i<=10; i++){
            System.out.printf("%s: %d * %d = %d\n",Thread.currentThread().getName(),number,i,i*number);
        }
    }
   
    /**
     * @param args
     */
    public staticvoidmain(String[] args) {
       
        //create 10 thread, chart one
        long t1 = System.currentTimeMillis();
        for(int i = 0 ; i < 10; i++){
            Worker worker = new Worker(i);
            Thread thread = new Thread(worker);
            thread.start();
        }
        System.out.println("-----------------------"+(System.currentTimeMillis() - t1));
 
    }
 
}
 


   在看另一个搜索文件的功能,扫描指定文件目录下的文件。完整代码如下:

 

import java.io.File;
import java.util.concurrent.TimeUnit;
 
public class FileSearchRunnable implements Runnable {
 
   
    /**
     * Initial path for the search
     */
    private StringinitPath;
    /**
     * Name of the file we are searching for
     */
    private StringfileName;
 
    /**
     * Constructor of the class
     *
     * @param initPath
     *           : Initial path for the search
     * @param fileName
     *           : Name of the file we are searching for
     */
    public FileSearchRunnable(String initPath, String fileName) {
        this.initPath = initPath;
        this.fileName = fileName;
    }
 
    /**
     * Main method of the class
     */
    @Override
    public voidrun() {
        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 thiscase, is empty
     */
    private voidcleanResources() {
 
    }
 
    /**
     * Method that process a directory
     *
     * @param file
     *           : Directory to process
     * @throws InterruptedException
     *            : If the thread is interrupted
     */
    private voiddirectoryProcess(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]);
                }
            }
        }
        // Check the interruption
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
 
    /**
     * Method that process a File
     *
     * @param file
     *           : File to process
     * @throws InterruptedException
     *            : If the thread is interrupted
     */
    private voidfileProcess(File file) throws InterruptedException {
        System.out.println("current file : "+file.getAbsolutePath());
        // Check the name
        if (file.getName().equals(fileName)) {
            System.out.printf("%s : %s\n",Thread.currentThread().getName(),file.getAbsolutePath());
            System.exit(0);
        }
 
        // Check the interruption
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
    }
    /**
     * @param args
     */
    public staticvoidmain(String[] args) {
        FileSearchRunnable searcher=new FileSearchRunnable("C:\\","USERPRIKEY.HS");
       
        Thread thread=new Thread(searcher);
       
        // Starts the Thread
        thread.start();
       
        // Wait for ten seconds
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
    }
 
}

 

Java并发编程之线程管理(上),布布扣,bubuko.com

Java并发编程之线程管理(上)

上一篇:不用concat解决Javascript连接多个数组


下一篇:深入理解Java Class文件格式(六)