最简单的多线程
多个独享资源的线程
最简单的利用多线程的情景就是有一些独占资源的任务,可以让多个线程同时去做,所谓独占资源就是每个线程的任务运行时所读写的变量或文件等资源都只有该线程会触碰到,比如说Java多线程概述中提到的搜索文件匹配字符串的问题,每次启动一个新的检查线程时,都会在赋给线程的任务中传入java文件的名字,由于每个线程只检索拿到的文件,而不会碰的线程的文件,因此不用考虑线程安全和线程通信的问题。
另一种情况:只读不改
像我们上课时,所有人都在各自阅读同一块黑板,个人阅读并不会影响别人阅读,也可以简单的多建立几个线程去各自阅读,由于暂时不考虑线程协作,所以每个人都是自己读自己的,并没有顺序之分(比如说A线程读第一段,B线程读第二段这样)。
总结
最简单的使用多线程的方式就是所有线程的任务都是独立运行互不影响的,可以是独占资源,也可以是同时只读同一个资源。
源代码
public class SearchFile {
/**
*
* @param file 查找的目录
* @param pattern 目标字符串
*/
public static void search(File file, String pattern) {
if (file.isFile()) {
new Thread(new CheckContentTask(file, pattern)).start();
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
search(f, pattern);
}
}
}
public static void main(String[] args) {
File folder = new File("src");
System.out.println(folder.isDirectory());
search(folder, "static");
}
}
// 独享资源的任务
class CheckContentTask implements Runnable {
private File file;
private String pattern;
public CheckContentTask(File file, String pattern) {
this.file = file;
this.pattern = pattern;
}
@Override
public void run() {
String fileContent = readFileContent(file); // 读取文件的内容
if (fileContent.contains(pattern)) {
System.out.format("在 %s 中匹配到了 %s %n", file.getAbsolutePath(), pattern);
}
}
public static String readFileContent(File file) {
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
char[] chars = new char[(int)file.length()];
fileReader.read(chars);
return new String(chars);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}