learned the operating system, suddenly do not know what is the use of multithreading.
Looked at Baidu, found multi-threading, can improve system utilization
At the time of the system IO operation, the CPU can handle some other things, and so on after IO reads into memory, the CPU is processed before the operation.
In summary can be at the user level, can improve efficiency, however, sometimes multithreaded design improper, debugging is also very troublesome
Today try a simple find file suffix in txt content demo
Seachfilecontent class for querying the contents of a file
Packagethread;ImportJava.io.File;Importjava.io.IOException; Public classseachfilecontent { Public Static voidMain (string[] args) {File file=NewFile ("D://tt//draymonder"); if(!file.exists ()) { Try{file.createnewfile (); } Catch(IOException e) {E.printstacktrace (); } }Else{String content= "Copy"; Searchfilecontent (file,content); } } Public Static voidsearchfilecontent (file file, String content) {if(File.isfile ()) {if(File.getname (). toLowerCase (). EndsWith (". txt")) { Newsearchfilethread (file, content). Start (); } } if(File.isdirectory ()) {file[] files=File.listfiles (); for(File singlefile:files) {searchfilecontent (singlefile, content); } } }}
Searchfilethread class , a query used to process the contents of a file in multithreading
Packagethread;ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException; Public classSearchfilethreadextendsThread {Privatefile file; PrivateString content; Searchfilethread () {} searchfilethread (file file, String content) { This. File =file; This. Content =content; } PrivateString getfilecontent (file file) {Try(FileReader FileReader =Newfilereader (file)) { Char[]all =New Char[(int) File.length ()]; Filereader.read (All); return NewString (All); }Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); return NULL; } }
@Override Public voidrun () {String str= Getfilecontent ( This. File); if(NULL!=str) { if(Str.contains ( This. Content)) {System.out.printf ("In%s contains the target string \"%s\ "...%n", This. File.getname (), This. Content); } } }}
Java Multithreading find content in a file