Java multithreading implementation and related operations

I have been working on competition projects for the past few months, and I will review some of the new knowledge I learned during the period.

1. There are two main implementation methods:

1. Inherit the java.lang.Thread class.

//创建新的线程对象
public class TestThread extends Thread{
    
     
public void run{
    
     
//功能实现代码
}
}
……
new TestThread().start()  //启动线程

2. Implement the java.lang.Runnable interface

//创建新类不继承Thread,实现Runnable接口
public class Text extends Objects implements Runnable{
    
    
  public void run{
    
    
  //功能实现代码}
 }
}

Implementing the Runnable interface creates a Thread object and associates the Runnable object with the Thread object. Thread contains two constructors.

public Thread(Runnable target)public Thread(Runable target,String name)

new Thread(new Runnable(){
    
    
public void run(){
    
    
//功能实现代码
 }
}).start;

2. Thread-related operations

1. Thread sleep
Call the sleep() method, in the run() method:
Thread.sleep(1000)//Thread sleeps for 1s
2. Thread joining
When a thread is executed, use the join() method to join another thread , This thread will not continue to execute until another thread ends.
3. Thread interruption
The current version abolishes the stop() method, and it is not recommended to use it to stop. Here, an infinite loop is used to terminate the loop with a Boolean value.

//定义类实现Runnable接口
public class Text extends Objects implements Runnable{
    
    
private boolean isContinue=true;
  public void run{
    
    
   //功能实现代码
  while(true){
    
    
  if(!isContinue){
    
    
     break;
      }
  
  
   }
//调用此方法控制布尔值
   public void setContinue(){
    
    
   this.isContinue=false;
   }
  }
 

Or when the thread enters the ready state using the sleep () method or the wait () method, you can use the interrupt () in the Thread class to make the thread leave the run () method and end the process at the same time.

Guess you like

Origin blog.csdn.net/qq_44706002/article/details/103244688