Java self study - multithreading starts a thread

Three ways to create a thread in Java

Multithreading means that you can do many things at the same time.

There are three ways to create multithreads: inherit thread class, implement Runnable interface and anonymous class

Step 1: thread concept

First, understand the difference between a process and a thread
Process: starting a LOL.exe is called a process. Then start a DOTA.exe, which is called two processes.
Threads: threads are things that are done at the same time within the process. For example, in LOL, there are many things to do at the same time, such as "Galen" killing "Timo" and "bounty hunter" killing "blind monk". This is achieved by multiple threads.

The code here demonstrates the situation of not using multithreading:
Only after Galen killed Timo did the bounty hunters begin to kill the blind monk

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 indicate that the attack takes time, each attack is suspended for 1000 milliseconds
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        h.hp-=damage;
        System.out.format("%s Attacking %s, %s The blood of %.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 = "Ti Mo";
        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 attacks Timo
        while(!teemo.isDead()){
            gareen.attackHero(teemo);
        }
 
        //Bounty Hunter attacks blind monk
        while(!leesin.isDead()){
            bh.attackHero(leesin);
        }
    }
     
}

Step 2: create multithread - inherit thread class

With multithreading, you can make Galen attack Timothy and the bounty hunter attack the blind monk
Design a class KillThread to inherit Thread and override run method
Start thread method: instantiate a KillThread object and call its start method
You can see that while the bounty hunters are attacking the blind monks, Galen is attacking Timo

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 = "Ti Mo";
        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 multithreading - implement Runnable interface

Create the class "Battle" to implement the Runnable interface
When starting, first create a battle object, then create a thread object based on the battle object, and start

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

The battle 1 object implements the Runnable interface, so there is a run method, but calling the run method directly does not start a new thread.
You must use the start() method of a thread object to start a new thread.
Therefore, when creating a Thread object, pass in battle 1 as a parameter of the construction method. When the Thread starts, it will execute the battle 1. Run () method.

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 = "Ti Mo";
        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 a multithreaded anonymous class

Using anonymous class, inheriting Thread, overriding run method, writing business code directly in run method
An advantage of anonymous classes is that they can easily access external local variables.
The premise is that external local variables need to be declared final. (not needed after JDK7)

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 = "Ti Mo";
        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(){
                //The external local variable teemo is used in anonymous class, and it must be declared as final
                //But after JDK7, it's not necessary to add final
                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: three ways to create multithreading

Reorganize the above three ways:

  1. Inherit Thread class
  2. Implement the Runnable interface
  3. How anonymous classes work

Note: the start thread is the start() method. run() cannot start a new thread

Practice: Find file contents synchronously

Change exercise find file content to multithread find file content
The idea of the original exercise is to traverse all files. When traversing to the file is. java, find the content of this file, and then traverse the next file after searching

Now adjust this idea through multithreading:
Traverse all files. When the file is. java, create a thread to find the contents of the file. Do not wait for the thread to finish, continue to traverse the next file

Answer:

First, prepare a SerachFileThread, inherit the Thread class, and override the run method. In the run method, read the contents of the file and find

Then when traversing the file, if it ends in. java, start a SerachFileThread thread thread to 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 document:%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 the. java file is found, a thread is started for 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");
    }
}

Keywords: Java

Added by ron814 on Tue, 25 Feb 2020 12:39:50 +0200