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.等待线程的终止
网友评论