Multithreading and concurrent programming [thread sleep, thread concession, thread union, judging whether the thread is alive] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

 

Table of contents

thread sleep

thread yield

thread union

Other common methods in the Thread class

Determine whether the thread is alive

thread priority


 

thread sleep

 sleep() method: It can make the running thread enter the blocked state until the sleep time is full and enter the ready state. The argument to the sleep method is the number of milliseconds to sleep.

public class SleepThread implements Runnable
{
    @Override
    public void run() {     
        System.out.println(Thread.currentThread().getName()+" 线程开始");
    for(int i=0;i<20;i++){
              System.out.println(Thread.currentThread().getName()+" "+i);
                try {
                    //线程休眠1秒
                    Thread.sleep(1000);
               } catch(InterruptedException e) {
                    e.printStackTrace();
               }
           }
      System.out.println(Thread.currentThread().getName()+" 线程结束");
   }
    public static void main(String[] args) {
        System.out.println("主线程开始");
        Thread t = new Thread(newSleepThread());
        t.start();
        System.out.println("主线程结束");
   }
}

thread yield

 yield() returns the currently running thread to the ready state to allow other threads of the same priority to get a chance to run. Therefore, the purpose of using yield() is to allow appropriate rotation between threads with the same priority. However, in practice, there is no guarantee that yield() will achieve the purpose of yielding, because the yielding thread may be selected again by the thread scheduler.

 A few points to note when using the yield method:

      1 yield is a static method.

      2 After calling yield, yield tells the current thread to give the running opportunity to a thread with the same priority.

      3 yield cannot guarantee that the current thread will quickly switch from the running state to the ready state.

      4 yield can only convert the current thread from the running state to the ready state, not the waiting or blocking state.

public class TestyieldThread implements Runnable {
    @Override
    public void run() {
        for(int i=0;i<30;i++){
            if("Thread0".equals(Thread.currentThread().getName())){
                if(i == 0){
                    Thread.yield();
               }
           }
          System.out.println(Thread.currentThread().getName()+" "+i);
       }
   }
    public static void main(String[] args) {
        Thread t1 = new Thread(newTestyieldThread());
        Thread t2 = new Thread(newTestyieldThread());
        t1.start();
        t2.start();
   }
}

thread union

 The current thread invites the thread calling the method to execute first, and the current thread cannot execute again until the thread calling the method finishes executing. During thread A running, you can call the join() method of thread B to join thread B and thread A. In this way, thread A must wait for thread B to finish executing before continuing to execute.

 Use of the join method

The join() method means that the thread that calls this method executes the code behind the join method after executing the run() method, that is, the two threads are merged to achieve synchronization control. 

class A implements Runnable{
    private Thread b;
    public A(Thread b){
        this.b = b;
   }
    @Override
    public void run() {
        for(int i=0;i<10;i++){
          System.out.println(Thread.currentThread().getName()+" A "+i);
            if(i == 5){
                try {
                    this.b.join();
               } catch(InterruptedException e) {
                    e.printStackTrace();
               }
           }
            try {
                Thread.sleep(1000);} catch (InterruptedException e){
                e.printStackTrace();
           }
       }
   }
}
class B implements Runnable{
    @Override
    public void run() {
        for(int i=0;i<20;i++){
          System.out.println(Thread.currentThread().getName()+" B "+i);
            try {
                Thread.sleep(1000);
           } catch (InterruptedException e){
                e.printStackTrace();
           }
       }
   }
}
public class TestJoinThread {
    public static void main(String[] args) {
        Thread t1 = new Thread(new B());
        Thread t = new Thread(new A(t1));
        t.start();
        t1.start();
 for(int i=0;i<10;i++){
          System.out.println(Thread.currentThread().getName()+" "+i);
            if(i ==2){
                try {
                    t.join();
               } catch(InterruptedException e) {
                    e.printStackTrace();
               }
           }
            try {
                Thread.sleep(1000);
           } catch (InterruptedException e){
                e.printStackTrace();
           }
       }
   }
}

thread union case

Requirements: Realize that the father asks the son to buy cigarettes.

/**
* 儿子买烟线程
*/
class SonThread implements Runnable{
    @Override
    public void run() {
        System.out.println("儿子出门买烟");
        System.out.println("儿子买烟需要10分钟");
        for(int i=0;i<10;i++){
            System.out.println("第"+i+"分钟");
            try {
                Thread.sleep(1000);
 } catch (InterruptedException e){
                e.printStackTrace();
           }
       }
        System.out.println("儿子买烟回来了");
   }
}
/**
* 爸爸抽烟线程
*/
class FatherThread implements Runnable{
    @Override
    public void run() {
        System.out.println("爸爸想抽烟,发现烟抽完了");
        System.out.println("爸爸让儿子去买一包红塔山");
        Thread t = new Thread(new SonThread());
        t.start();
        System.out.println("等待儿子买烟回来");
        try {
            t.join();
       } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("爸爸出门找儿子");
            System.exit(1);
       }
  System.out.println("爸爸高兴的接过烟,并把零钱给了儿子");
   }
}
public class TestJoinDemo {
    public static void main(String[] args) {
        System.out.println("爸爸和儿子买烟的故事");
        Thread t = new Thread(new FatherThread());
        t.start();
   }
}

Other common methods in the Thread class

Get the current thread name

Method 1: this.getName() to obtain the thread name, this method is suitable for inheriting Thread to implement multi-threading.

class GetName1 extends Thread{
    @Override
    public void run() {
        System.out.println(this.getName());
   }
}

Method 2: Thread.currentThread().getName() to obtain the thread name, this method is suitable for implementing the Runnable interface to realize multi-threading.

class GetName2 implements Runnable{
    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName());
   }
}

Set the name of the thread

Method 1: Set the thread name through the constructor.

class SetName1 extends Thread{
    public SetName1(String name){
        super(name);
   }
    @Override
    public void run() {
        System.out.println(this.getName());
   }
}
public class SetNameThread {
    public static void main(String[] args) {
        SetName1 setName1 = new SetName1("SetName1");
        setName1.start();
   }
}

Method 2 Set the thread name through the setName() method.

class SetName2 implements Runnable{
    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName());
   }
}
public class SetNameThread {
    public static void main(String[] args) {
        Thread thread = new Thread(new SetName2());
        thread.setName("SetName2");
        thread.start();
   }
}

Determine whether the thread is alive

 isAlive() method: Determine whether the current thread is active. The active state means that the thread has been started and has not been terminated. If the thread is running or ready to start running, the thread is considered to be alive.

class Alive implements  Runnable{
    @Override
    public void run() {
        for(int i=0;i<4;i++){
          System.out.println(Thread.currentThread().getName()+" "+i);
            try {
                Thread.sleep(500);
           } catch (InterruptedException e){
                e.printStackTrace();
           }
       }
   }
}
public class TestAliveThread {
    public static void main(String[] args) {
        Thread thread = new Thread(newAlive());
        thread.setName("Alive");
        thread.start();
      System.out.println(thread.getName()+" "+thread.isAlive());
        try {
            Thread.sleep(4000);
       } catch (InterruptedException e) {
            e.printStackTrace();
       }
      System.out.println(thread.getName()+""+thread.isAlive());
   }
}

thread priority

 What is thread priority

Each thread has a priority, we can define the priority of the thread for each thread, but this does not guarantee that the high priority thread will be executed before the low priority thread. The priority of a thread is represented by a number, ranging from 1 to 10, and the default priority of a thread is 5. Java's thread priority scheduling will be entrusted to the operating system to handle, so it is related to the specific operating system priority. If there is no special need, generally there is no need to set the thread priority.

Notice

The priority of the thread does not mean which thread is executed first, if the priority of a certain thread is set high. That is, there is a high probability of being executed. It is not a priority.

 Use of thread priority

Use the following methods to get or set the thread object's priority.

1 int getPriority();

2 void setPriority(int newPriority);

Note: A low priority simply means a low probability of getting scheduled. It is not absolutely necessary to call a thread with a high priority first and then a thread with a low priority.

class Priority implements Runnable{
    private int num = 0;
    private  boolean flag = true;
    @Override
    public void run() {
        while(this.flag){
          System.out.println(Thread.currentThread().getName()+" "+num++);
       }
   }
    public void stop(){  
        this.flag = false;
   }
}
public class PriorityThread {
    public static void main(String[] args)throws Exception {
        Priority p1 = new Priority();
        Priority p2 = new Priority();
        Thread t1 = new Thread(p1,"线程1");
        Thread t2 = new Thread(p2,"线程2");
        System.out.println(t1.getPriority());
        //Thread.MAX_PRIORITY = 10
        t1.setPriority(Thread.MAX_PRIORITY);
        //Thread.MAX_PRIORITY = 1
        t2.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.start();
        Thread.sleep(1000);
        p1.stop();
        p2.stop();
   }
}

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131648197