inotgo.com


Tool version compatibility problem
Multithreading means that at the same time , Can do many things .

Creating multithreading has 3 Two ways , namely Inherit thread class , realization Runnable Interface , Anonymous class
Correct

This video is interpretive , So I hope you have read the content of this knowledge point , And after writing the corresponding code , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning



16 branch 13 second
This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers



Step 1 : Thread concept   
Step 2 : Create multithreaded - Inherit thread class   
Step 3 : Create multithreaded - realization Runnable Interface   
Step 4 : Create multithreaded - Anonymous class   
Step 5 : There are three ways to create multithreading   
Step 6 : practice - Find file contents synchronously   
Step 7 : answer - Find file contents synchronously   

First, understand the process (Processor) And threads (Thread) The difference between
Process : Start a LOL.exe It's called a process . Then start another DOTA.exe, This is called two processes .
Thread : Threads are things that are done simultaneously within a process , For example, in LOL in , There are many things to do at the same time , For example " Galen ” Kill “ Timo ”, At the same time “ Bounty Hunter ” Killing again “ Blind monk ”, This is achieved by multithreading .


The code here demonstrates Without multithreading
Only after Galen killed Timo , Bounty hunters began to kill blind monks
 Thread concept
package charactor; import java.io.Serializable; public class Hero{ public String name; public float hp; public int damage; public void attackHero(Hero h) { try { // To show that the attack takes time , Every attack is suspended 1000 millisecond Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } h.hp-=damage; System.out.format("%s Attacking %s, %s My blood became %.0f%n",name,h.name,h.name,h.hp); if(h.isDead()) System.out.println(h.name +" Dead !"); } public boolean isDead() { return 0>=hp?true:false; } }
package multiplethread; import charactor.Hero; public class TestThread { public static void main(String[] args) { Hero gareen = new Hero(); gareen.name = " Galen "; gareen.hp = 616; gareen.damage = 50; Hero teemo = new Hero(); teemo.name = " Timo "; teemo.hp = 300; teemo.damage = 30; Hero bh = new Hero(); bh.name = " Bounty Hunter "; bh.hp = 500; bh.damage = 65; Hero leesin = new Hero(); leesin.name = " Blind monk "; leesin.hp = 455; leesin.damage = 80; // Galen attacked Timo while(!teemo.isDead()){ gareen.attackHero(teemo); } // Bounty hunters attack blind monks while(!leesin.isDead()){ bh.attackHero(leesin); } } }
Step 2 :

Create multithreaded - Inherit thread class

edit top fracture
Use multithreading , You can do what Galen is attacking Timo At the same time , Bounty hunters are also attacking blind monks
Design a class KillThread Inherit Thread, And rewrite run method
Start thread method : Instantiate a KillThread Object , And call its start method
You can observe The bounty hunter attacked the blind monk At the same time , Galen is also attacking Timo
 Create multithreaded - Inherit thread class
package multiplethread; import charactor.Hero; public class KillThread extends Thread{ private Hero h1; private Hero h2; public KillThread(Hero h1, Hero h2){ this.h1 = h1; this.h2 = h2; } public void run(){ while(!h2.isDead()){ h1.attackHero(h2); } } }
package multiplethread; import charactor.Hero; public class TestThread { public static void main(String[] args) { Hero gareen = new Hero(); gareen.name = " Galen "; gareen.hp = 616; gareen.damage = 50; Hero teemo = new Hero(); teemo.name = " Timo "; teemo.hp = 300; teemo.damage = 30; Hero bh = new Hero(); bh.name = " Bounty Hunter "; bh.hp = 500; bh.damage = 65; Hero leesin = new Hero(); leesin.name = " Blind monk "; leesin.hp = 455; leesin.damage = 80; KillThread killThread1 = new KillThread(gareen,teemo); killThread1.start(); KillThread killThread2 = new KillThread(bh,leesin); killThread2.start(); } }
Step 3 :

Create multithreaded - realization Runnable Interface

edit top fracture
Create class Battle, realization Runnable Interface
When starting , First create a Battle Object , Then according to the battle Object to create a thread object , And start

Battle battle1 = new Battle(gareen,teemo);
new Thread(battle1).start();

battle1 Object implements Runnable Interface , So there are run method , But call directly run method , Does not start a new thread .
must , With the help of a thread object start() method , Will start a new thread .
So , In creating Thread Object time , hold battle1 Pass it in as a parameter of the constructor , When this thread starts , Will execute battle1.run() The method is .

package multiplethread; import charactor.Hero; public class Battle implements Runnable{ private Hero h1; private Hero h2; public Battle(Hero h1, Hero h2){ this.h1 = h1; this.h2 = h2; } public void run(){ while(!h2.isDead()){ h1.attackHero(h2); } } }
package multiplethread; import charactor.Hero; public class TestThread { public static void main(String[] args) { Hero gareen = new Hero(); gareen.name = " Galen "; gareen.hp = 616; gareen.damage = 50; Hero teemo = new Hero(); teemo.name = " Timo "; teemo.hp = 300; teemo.damage = 30; Hero bh = new Hero(); bh.name = " Bounty Hunter "; bh.hp = 500; bh.damage = 65; Hero leesin = new Hero(); leesin.name = " Blind monk "; leesin.hp = 455; leesin.damage = 80; Battle battle1 = new Battle(gareen,teemo); new Thread(battle1).start(); Battle battle2 = new Battle(bh,leesin); new Thread(battle2).start(); } }
Step 4 :

Create multithreaded - Anonymous class

edit top fracture
use Anonymous class , Inherit Thread, rewrite run method , Directly in run Write business code in method
One advantage of anonymous classes is that they can easily access external local variables .
The premise is that external local variables need to be declared as final.(JDK7 It won't be needed in the future )
package multiplethread; import charactor.Hero; public class TestThread { public static void main(String[] args) { Hero gareen = new Hero(); gareen.name = " Galen "; gareen.hp = 616; gareen.damage = 50; Hero teemo = new Hero(); teemo.name = " Timo "; teemo.hp = 300; teemo.damage = 30; Hero bh = new Hero(); bh.name = " Bounty Hunter "; bh.hp = 500; bh.damage = 65; Hero leesin = new Hero(); leesin.name = " Blind monk "; leesin.hp = 455; leesin.damage = 80; // Anonymous class Thread t1= new Thread(){ public void run(){ // External local variables are used in anonymous classes teemo, We must put teemo Declare as final // But in JDK7 in the future , You don't have to add final Yes while(!teemo.isDead()){ gareen.attackHero(teemo); } } }; t1.start(); Thread t2= new Thread(){ public void run(){ while(!leesin.isDead()){ bh.attackHero(leesin); } } }; t2.start(); } }
Step 5 :

There are three ways to create multithreading

edit top fracture
Put the above 3 Sort it out in two ways :

1. Inherit Thread class
2. realization Runnable Interface
3. Anonymous classes

notes : The starting thread is start() method ,run() Can't start a new thread
Step 6 :

practice - Find file contents synchronously

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
hold practice - Find the contents of the file Change to multithreading to find the contents of the file
The idea of the original exercise is to traverse all files , When traversing to the file is .java When I was , Find the contents of this file , After searching , Then traverse the next file

Now adjust this idea through multithreading :
Traverse all files , When traversing to the file is .java When I was , Create a thread to find the contents of this file , You don't have to wait for this thread to end , Continue to traverse the next file
Step 7 :

answer - Find file contents synchronously

edit top fracture
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Viewing this answer will cost 4 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Viewing this answer will cost 4 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Account not activated Account not activated , Limited functionality . Please click activate
This video is interpretive , So I hope you have read the content of this answer , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning

6 branch 33 second This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers


First prepare a SerachFileThread, Inherit Thread class , And rewrite run method . stay run In the method , Read file contents and find

Then when traversing the file , If so .java ending , Then start a SerachFileThread Thread , Do the search
package multiplethread; import java.io.File; import java.io.FileReader; import java.io.IOException; public class SearchFileThread extends Thread{ private File file; private String search; public SearchFileThread(File file,String search) { this.file = file; this.search= search; } public void run(){ String fileContent = readFileConent(file); if(fileContent.contains(search)){ System.out.printf(" Sub target string found %s, In the file :%s%n",search,file); } } public String readFileConent(File file){ try (FileReader fr = new FileReader(file)) { char[] all = new char[(int) file.length()]; fr.read(all); return new String(all); } catch (IOException e) { e.printStackTrace(); return null; } } }
package multiplethread; import java.io.File; public class TestThread { public static void search(File file, String search) { if (file.isFile()) { if(file.getName().toLowerCase().endsWith(".java")){ // When you find .java When you file , Just start a thread , Make a special search new SearchFileThread(file,search).start(); } } if (file.isDirectory()) { File[] fs = file.listFiles(); for (File f : fs) { search(f, search); } } } public static void main(String[] args) { File folder =new File("e:\\project"); search(folder,"Magic"); } }


The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .


Q & A area    
2021-10-09 Multithreading to find file contents
wait4132




hold practice - Find the contents of the file Change to multithreading to find the contents of the file The idea of the original exercise is to traverse all files , When traversing to the file is .java When I was , Find the contents of this file , After searching , Then traverse the next file Now adjust this idea through multithreading : Traverse all files , When traversing to the file is .txt When I was , Create a thread to find the contents of this file , You don't have to wait for this thread to end , Continue to traverse the next file
package Thread;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class MultiThreading {
	// Multithreading to find file contents 
	
public static void main(String[] args) {
	File f=new File("E:\\how2j.com\\ Multithreading to find files ");
	Find.find(f);
}
}
class Check extends Thread
{
	String fn;
	public Check(String fn)
	{
		this.fn=fn;
	}
	public void run()
	{
		try
		{
			// Thread pause 
			Thread.sleep(1000);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		// The contents of the output file 
		File f=new File(fn);
		try(FileReader in=new FileReader(f);
				BufferedReader bin=new BufferedReader(in);)
		{
			
			StringBuffer s=new StringBuffer();
			String line;
			while((line=bin.readLine())!=null)
			{
				s.append(line+"\n");
				
			}
			System.out.println(s);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
class Find
{
	public static void find(File f)
	{
		if(!f.exists())return;
		File[] fs=f.listFiles();
		for(File f1:fs)
		{
			if(f1.isFile())
			{
			// If it is a file, judge whether the file suffix is .txt	
			String[] s1=f1.getName().split("\\.");
			// Not in the form of "." As a separation "." Is a special character that needs to be escaped 
			if(s1.length!=0&&s1[s1.length-1].equals("txt"))
				// To determine the equality of strings, you need to use equals out-of-service ==
			{
				// yes txt File words , Create the contents of the thread output 
				Check c=new Check(f1.getAbsolutePath());
				c.start();
			}
			}
			else if(f1.isDirectory())
				// If it's a folder, recursively traverse 
			{
				find(f1);
			}
		}
		
	}
}
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-08-22 It should be right , Interleaved different documents
Black vortex




hold practice - Find the contents of the file Change to multithreading to find the contents of the file The idea of the original exercise is to traverse all files , When traversing to the file is .java When I was , Find the contents of this file , After searching , Then traverse the next file Now adjust this idea through multithreading : Traverse all files , When traversing to the file is .java When I was , Create a thread to find the contents of this file , You don't have to wait for this thread to end , Continue to traverse the next file
 Loading
public static void main(String[] args) {
        File file = new File("D:\\project\\tmall_ssm");
        String name = "a";
        one one = new one();
        one.search(file,name);
    }

    public void search(File file,String name){
//        System.out.println(" The file name is "+file);
        File[] files = file.listFiles();
        for (int i = 0;i < files.length;i++) {
            File f = files[i];
            if (files[i].getName().contains(name)) {
                System.out.printf(" The thread has found a file containing %s My files , file location %s\r\n", name, files[i].getAbsolutePath());
                if (files[i].isDirectory()) {
                    new Thread() {
                        @Override
                        public void run() {
                            System.out.println(" Thread created ");
                            search(f, name);
                        }
                    }.start();
                }
            } else {
                if (f.isDirectory()) {
                    search(f, name);
                }
            }
        }
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-08-01 practice - Find the contents of the file
2021-07-23 Why don't the stationmaster demonstrate that the five dogs fly together 、Tab Flicker
2021-03-25 Threads and for Cycle


Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 58 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Intermediate - Multithreading - Start a thread Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot