Java self study - multithreading common thread method

Common Java threading methods

Example 1: current thread pause

Thread.sleep(1000); indicates that the current thread is suspended for 1000 milliseconds, and other threads are not affected
Thread.sleep(1000); an InterruptedException interrupt exception will be thrown because the current thread sleep may be stopped, and InterruptedException will be thrown

package multiplethread;
 
public class TestThread {
 
    public static void main(String[] args) {
         
        Thread t1= new Thread(){
            public void run(){
                int seconds =0;
                while(true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.printf("Already played. LOL %d second%n", seconds++);
                }              
            }
        };
        t1.start();
         
    }
     
}

Example 2: adding to the current thread

First, explain the concept of main thread
All processes, at least one thread is the main thread, that is, when the main method starts executing, there will be an invisible main thread.
Executing t.join on line 42 indicates that the thread is added to the main thread.
The main thread will wait for the end of the thread before running down.

package multiplethread;
  
import charactor.Hero;
  
public class TestThread {
  
    public static void main(String[] args) {
          
        final Hero gareen = new Hero();
        gareen.name = "Galen";
        gareen.hp = 616;
        gareen.damage = 50;
  
        final Hero teemo = new Hero();
        teemo.name = "Ti Mo";
        teemo.hp = 300;
        teemo.damage = 30;
          
        final Hero bh = new Hero();
        bh.name = "Bounty Hunter";
        bh.hp = 500;
        bh.damage = 65;
          
        final Hero leesin = new Hero();
        leesin.name = "Blind monk";
        leesin.hp = 455;
        leesin.damage = 80;
          
        Thread t1= new Thread(){
            public void run(){
                while(!teemo.isDead()){
                    gareen.attackHero(teemo);
                }              
            }
        };
          
        t1.start();
 
        //The main thread has been running since the code was executed
        try {
            //t1 thread is added to main thread. Only when t1 thread finishes running, can it continue to go down
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        Thread t2= new Thread(){
            public void run(){
                while(!leesin.isDead()){
                    bh.attackHero(leesin);
                }              
            }
        };
        //It will be observed that Galen kills Timo before running the t2 thread
        t2.start();
          
    }
      
}

Example 3: thread priority

When a thread is in a competitive relationship, a higher priority thread will have a greater chance to obtain CPU resources
In order to demonstrate this effect, to remove the pause time, multiple threads will try their best to occupy CPU resources
At the same time, increase the hero's HP by 100 times and reduce the attack to 1, so that you have enough time to observe the priority demonstration
As can be seen from the figure, the priority of thread 1 is max? Priority, so it gains more CPU resources to execute the code

  package charactor;
      
    import java.io.Serializable;
       
    public class Hero{
        public String name;
        public float hp;
          
        public int damage;
          
        public void attackHero(Hero h) {
            //Remove the pause time, and multiple threads will try their best to occupy CPU resources
            //The priority effect of threads can be seen
    //        try {
    //           
    //            Thread.sleep(0);
    //        } 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) {
          
        final Hero gareen = new Hero();
        gareen.name = "Galen";
        gareen.hp = 6160;
        gareen.damage = 1;
  
        final Hero teemo = new Hero();
        teemo.name = "Ti Mo";
        teemo.hp = 3000;
        teemo.damage = 1;
          
        final Hero bh = new Hero();
        bh.name = "Bounty Hunter";
        bh.hp = 5000;
        bh.damage = 1;
          
        final Hero leesin = new Hero();
        leesin.name = "Blind monk";
        leesin.hp = 4505;
        leesin.damage = 1;
          
        Thread t1= new Thread(){
            public void run(){
 
                while(!teemo.isDead()){
                    gareen.attackHero(teemo);
                }              
            }
        };
          
        Thread t2= new Thread(){
            public void run(){
                while(!leesin.isDead()){
                    bh.attackHero(leesin);
                }              
            }
        };
         
        t1.setPriority(Thread.MAX_PRIORITY);
        t2.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
          
    }
      
}

Example 4: temporary pause

The current thread is temporarily suspended, so that other threads have more opportunities to occupy CPU resources

package multiplethread;
  
import charactor.Hero;
  
public class TestThread {
  
    public static void main(String[] args) {
          
        final Hero gareen = new Hero();
        gareen.name = "Galen";
        gareen.hp = 61600;
        gareen.damage = 1;
  
        final Hero teemo = new Hero();
        teemo.name = "Ti Mo";
        teemo.hp = 30000;
        teemo.damage = 1;
          
        final Hero bh = new Hero();
        bh.name = "Bounty Hunter";
        bh.hp = 50000;
        bh.damage = 1;
          
        final Hero leesin = new Hero();
        leesin.name = "Blind monk";
        leesin.hp = 45050;
        leesin.damage = 1;
          
        Thread t1= new Thread(){
            public void run(){
 
                while(!teemo.isDead()){
                    gareen.attackHero(teemo);
                }              
            }
        };
          
        Thread t2= new Thread(){
            public void run(){
                while(!leesin.isDead()){
                    //Pause temporarily so that t1 can occupy CPU resources
                    Thread.yield();
                     
                    bh.attackHero(leesin);
                }              
            }
        };
         
        t1.setPriority(5);
        t2.setPriority(5);
        t1.start();
        t2.start();
          
    }
      
}

Example 5: Daemons

The concept of daemons is: when all threads in a process are daemons, the current process is ended.

It's like a company has sales department and production department, which are related to business.
In addition, there are logistics, administration and other support departments.

If a company's sales department and production department are dissolved, only logistics and administration are left, then the company can also be dissolved.

Daemons are the same as those supporting departments. If there are only daemons left in a process, the process will automatically end.

Daemons are usually used for logging, performance statistics, etc.

package multiplethread;
  
public class TestThread {
  
    public static void main(String[] args) {
          
        Thread t1= new Thread(){
            public void run(){
                int seconds = 0;
                 
                while(true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.printf("Already played. LOL %d second%n", seconds++);
                     
                }              
            }
        };
        t1.setDaemon(true);
        t1.start();
          
    }
      
}

Practice: Crack password

  1. Generate a random string with a length of 3. Use this string as a password

  2. Create a cracking thread, use exhaustive method to match the password

  3. Create a log thread and print which strings are used to match. This log thread is designed as a guardian thread

Tip: the cracking thread puts the possible password generated by the exhaustive method into a container, and the log thread constantly takes out the possible password from the container and prints it out. If it is found that the container is empty, it will rest for 1 second. If it is not empty, it will be taken out continuously and printed.

Answer:

Threads that exhaust passwords

package multiplethread;
 
import java.util.List;
 
public class PasswordThread extends Thread{
 
    private boolean found = false;
     
    private String password;
 
    private List<String> passwords;
 
    public PasswordThread(String password, List<String> passwords) {
        this.password = password;
        this.passwords = passwords;
    }
     
    public void run(){
        char[] guessPassword = new char[password.length()];
        generatePassword(guessPassword, password);
    }
 
    public  void generatePassword(char[] guessPassword, String password) {
        generatePassword(guessPassword, 0, password);
    }
 
    public  void generatePassword(char[] guessPassword, int index, String password) {
        if (found)
            return;
        for (short i = '0'; i <= 'z'; i++) {
            char c = (char) i;
            if (!Character.isLetterOrDigit(c))
                continue;
            guessPassword[index] = c;
            if (index != guessPassword.length - 1) {
                generatePassword(guessPassword, index + 1, password);
            } else {
                String guess = new String(guessPassword);
                //Exhaust every password generated, put it into the set
                passwords.add(guess);
                if (guess.equals(password)) {
                    System.out.println("Yes, the password is" + guess);
                    found = true;
                    return;
                }
                 
            }
        }
    }
     
}

Logging Daemons

package multiplethread;
 
import java.util.List;
 
public class LogThread extends Thread{
    private boolean found = false;
 
    private List<String> passwords;
 
    public LogThread(List<String> passwords) {
        this.passwords = passwords;
         
        this.setDaemon(true);//Set the thread of logging as the guardian thread
    }
     
    public void run(){
        while(true){
            while(passwords.isEmpty()){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
             
            String password = passwords.remove(0);
            System.out.println("The password generated by exhaustive method this time is:" +password);
        }
    }
     
}

Test class

package multiplethread;
 
import java.util.ArrayList;
import java.util.List;
 
public class TestThread {
 
    public static boolean found = false;
     
    public static void main(String[] args) {
        String password = randomString(3);
        System.out.println("The password is:" + password);
        List<String> passwords = new ArrayList<>();
         
        new PasswordThread(password,passwords).start();
        new LogThread(passwords).start();
         
    }
 
    private static String randomString(int length) {
        String pool = "";
        for (short i = '0'; i <= '9'; i++) {
            pool += (char) i;
        }
        for (short i = 'a'; i <= 'z'; i++) {
            pool += (char) i;
        }
        for (short i = 'A'; i <= 'Z'; i++) {
            pool += (char) i;
        }
        char cs[] = new char[length];
        for (int i = 0; i < cs.length; i++) {
            int index = (int) (Math.random() * pool.length());
            cs[i] = pool.charAt(index);
        }
        String result = new String(cs);
        return result;
    }
 
}

Keywords: Java REST

Added by peterjoel on Wed, 26 Feb 2020 13:51:30 +0200