当前位置:网站首页>Thread status (timed wait, lock blocking, infinite wait (key))

Thread status (timed wait, lock blocking, infinite wait (key))

2022-06-22 08:17:00 Hanxiaozhi

One : Thread state

1. Thread state overview ( Yes 6 Thread status in )
①:new( newly build )– Thread just created , But it didn't start . Not yet called start Method .
②:Runnable( Can run ) -- Threads can be in java State of running in virtual machine , You may be running your own code , Or maybe not , It depends on the operating system processor .
③:Blocked( The lock is blocked )– When a thread attempts to acquire an object lock , The object lock is held by other threads , Then the thread enters Blocked state ; When the thread holds the lock , The thread will become Runnable state .
④:Waiting( Wait indefinitely )– One thread is waiting for another to execute a ( Wake up the ) In action , The thread enters Waiting state . You can't wake up automatically after entering this state , You have to wait for another thread to call notify perhaps notifyAll Method to wake up .
⑤:Timed Waiting( Time wait for )– Same as waiting state , There are several methods that have timeout parameters , Call them and they will enter Timed Waiting state . This state will remain until the timeout period has expired or a wake-up notification has been received . Common methods with timeout parameters are Thread.sleep 、Object.wait.
⑥:Teminated( Terminated )– because run Method normal exit and death , Or it's terminated because there's no exception caught run The way to die .

The picture shows
 Insert picture description here

2. Time wait for
Example :
// Demonstrates the sleep state of a thread
class ThreadSleep implements Runnable {
// Create thread task , Analog alarm clock
public void run() {
// 10 Second alarm clock will automatically alarm
for( int i = 1; i <= 10; i++ ) {
// Analog output seconds
System.out.println(“ The first ”+ i +“ second !”);
// Let the thread rest 1000 millisecond
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(“ Tinkling bell …”);
}
}
public class ThreadSleepDemo {
public static void main(String[] args) {
// Create thread task
ThreadSleep ts = new ThreadSleep();
// Creating thread objects
Thread t = new Thread( ts );
// Start thread task
t.start();
}
}

3. The lock is blocked
Threads A With threads B The same lock is used in the code , If the thread A Get lock , Threads A Enter into Runnable state , So thread B Just enter Blocked Lock blocked .
Simply speaking , It is the thread that does not acquire the lock after startup . In this state .

4. Wait indefinitely

4.1. producers and consumers

①: producers and consumers ( Application scenarios )– Multiple threads are processing the same shared resource container , But the way it is handled ( Thread tasks ) But not the same .
②: Example : Threads A Used to generate packages and put them into the resource container , Threads B It's eating steamed buns from containers , The container for storing the buns can be understood as the same resource , Threads A With threads B The action of processing , One is production , One is consumption , So thread A With threads B There is a thread communication problem between .
③: Shared resource container :
// Resource container class
public class BaoZiPu {
/*
Define an array , Serve as a container for keeping buns .
If the data stored in the array is null, There are no buns in the container
If the data stored in the array is not null, It means that there are steamed buns in the container
/
private String[] str = new String[1];
// Defining variables , Record the number of steamed buns produced
private int count = 1;
// Define the lock object
private Object lock = new Object();
/

There are two types of container based operations :
One is to save data in the container
One is to take data out of the container
*/
// The way to keep the buns in the container
public void add( String name ) {
synchronized ( lock ) {
try {Thread.sleep(10);}catch(InterruptedException e) {}
// Save the buns
str[0] = name + count;
System.out.println(“ The producer keeps... In containers …” + str[0]);
// After saving , A variable that records the number of packages +1
count++;
}
}
// How to take the steamed stuffed bun out of the container
public void get(){
synchronized ( lock ) {
try {Thread.sleep(10);}catch(InterruptedException e) {}
// Print simulation package and take it out
System.out.println(“ Consumer removes from container …” + str[0]);
// After the steamed stuffed bun is taken out , Set the container space null
str[0] = null;
}
}
}

Producer class :
// Generator thread
public class Producer implements Runnable {
// Define resource container objects
private BaoZiPu bzp;
// Construction method , When you create an object , Assign a value to the resource container object
public Producer( BaoZiPu bzp ) {
this.bzp = bzp;
}

//  The thread task is to save the package to the container 
public void run() {
    //  Call the saved method 
    while( true ) {
        bzp.add(" Big steamed stuffed bun with fat meat ...");
    }
}

}

Consumer class :
// Consumer thread
public class Consumer implements Runnable{
// Define resource container objects
private BaoZiPu bzp;
// Construction method , When you create an object , Assign a value to the resource container object
public Consumer(BaoZiPu bzp) {
this.bzp = bzp;
}

//  The thread task is to take the package from the container 
public void run() {
    while( true ) {
        bzp.get();
    }
}

}

Test class :
public class ProducerConsumerDemo {
public static void main(String[] args) {
// Create a shared resource package sub store object
BaoZiPu bzp = new BaoZiPu();
// Create a producer thread task object
Producer pro = new Producer( bzp );
// Create a consumer thread task object
Consumer con = new Consumer( bzp );

    //  Create a producer thread object 
    Thread pro_thread = new Thread( pro );
    //  Create a consumer thread object 
    Thread con_thread = new Thread( con );
    //  Start the producer and consumer thread tasks 
    pro_thread.start();
    con_thread.start();
}

}

4.2. Thread communication ( To realize the communication between threads , You need to use the wait for wakeup mechanism .)

  • void wait() Causes the current thread to wait , Until another thread calls it notify() or notifyAll() Method to wake it up .

    • Thread calls wait() Method , Will release its ownership of the lock , Then wait for another thread to wake it up , In this way, it can regain the ownership of the lock and resume execution .
  • void notify() Wake up the waiting object monitor ( arbitrarily ) Single thread . The wakeup thread is random .

  • void notifyAll() Wake up all threads waiting for the object monitor .

4.3. Wait for the wake-up mechanism

// Resource container class
/*
Add a wake-up waiting mechanism , Solve the problem of mass storage and retrieval
/
public class BaoZiPu {
/

Define an array , Serve as a container for keeping buns .
If the data stored in the array is null, There are no buns in the container
If the data stored in the array is not null, It means that there are steamed buns in the container
*/

private String[] str = new String[1];

//  Defining variables , Record the number of steamed buns produced 
private int count = 1;

//  Define the lock object 
private Object lock = new Object();
/*
     There are two types of container based operations :
         One is to save data in the container 
         One is to take data out of the container 
 */
//  The way to keep the buns in the container 
public void add( String name ) {
    synchronized ( lock ) {
        //  Before you save the buns in a container , First determine whether there are steamed buns in the container 
        if( str[0] != null ) {
            //  There are buns in the container , Call wait Methods make producers wait 
            try {lock.wait();} catch (InterruptedException e) {}
        }

        try {Thread.sleep(10);} catch (InterruptedException e) {}
        //  Save the buns 
        str[0] = name + count;
        System.out.println(" The producer keeps... In containers ..." + str[0]);
        //  After saving , A variable that records the number of packages +1
        count++;

        //  The code executes here , It indicates that the product has been saved , Awaken consumers to consume goods 
        lock.notify();
    }
}
//  How to take the steamed stuffed bun out of the container 
public void get(){
    synchronized ( lock ) {
        //  Before removing the steamed stuffed bun from the container , First determine whether there are steamed buns in the container 
        if( str[0] == null ) {
            //  There are no buns in the container , Call wait Methods make consumers wait 
            try {lock.wait();} catch (InterruptedException e) {}
        }
        try {Thread.sleep(10);} catch (InterruptedException e) {}
        //  Print simulation package and take it out 
        System.out.println(" Consumer removes from container ....." + str[0]);
        //  After the steamed stuffed bun is taken out , Set the container space null
        str[0] = null;

        //  The code executes here , It means that the goods have been consumed , Wake up the producer to generate the product 
        lock.notify();
    }
}

}

原网站

版权声明
本文为[Hanxiaozhi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220528500174.html