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.等待線程的終止