search
HomeJavajavaTutorialSample code for multi-thread blocking and wake-up in Java

This article mainly shares with you the relevant content about blocking and waking up in Java multi-threading. Through this article, you can roughly understand the methods of entering the thread blocking state and executable state. Friends who need it can learn about it.

Java thread blocking and waking up

1. sleep() method:

sleep (...milliseconds), specifies the time in milliseconds, so that the thread enters the thread blocking state within this time, during which the CPU time slice is not obtained. When the time passes, the thread re-enters the executable state. (Suspending the thread, the lock will not be released)


//测试sleep()方法
class Thread7 implements Runnable{
  @Override
  public void run() {
    for(int i=0;i<50;i++){
      System.out.println(Thread.currentThread().getName()+"num="+i);
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
class Thread8 implements Runnable{
  @Override
  public void run() {
    for(int i=0;i<1000;i++){
      System.out.println(Thread.currentThread().getName()+"num="+i);
    }
  }
}
public static void main(String[] args) {
    /*
     * 测试线程阻塞
     */
    //测试sleep()方法
    Thread7 t7=new Thread7();
    Thread8 t8=new Thread8();
    Thread t81=new Thread(t8, "饺子");
    Thread t71=new Thread(t7, "包子");
    Thread t72=new Thread(t7, "面包");
    t71.start();
    t81.start();
    t72.start();
  }

2.suspend() and resume() methods:.

To suspend and wake up threads, suspend() puts the thread into a blocking state. Only when the corresponding resume() is called, the thread will enter the executable state. (Not recommended, deadlock is prone to occur)


//测试suspend()和resume()方法
class Thread9 implements Runnable{
  @Override
  public void run() {
    for(long i=0;i<500000000;i++){
System.out.println(Thread.currentThread().getName()+" num= "+i);
    }
  }
}
public static void main(String[] args) {
  //测试suspend和resume
    Thread9 t9=new Thread9();
    Thread t91=new Thread(t9,"包子");
    t91.start();
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    t91.suspend();
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    t91.resume();
}

(When the console prints output, it will pause for 2 seconds and then continue printing.)

3. yield() method:

will cause the thread to give up the current CPU time slice, but the thread is still executable at this time status, the CPU time slice can be allocated again at any time. The yield() method can only give threads of the same priority a chance to execute. The effect of calling yield() is equivalent to the scheduler deeming that the thread has executed enough time to move to another thread. (Pause the currently executing thread and execute other threads, and the time to give up is unknown)


//测试yield()方法
class Thread10 implements Runnable{
  @Override
  public void run() {
    for(int i=0;i<100;i++){
      System.out.println(Thread.currentThread().getName()+" num= "+i);
      if(i==33){
        Thread.yield();
      }
    }
  }
}

public static void main(String[] args) {
  //测试yield
    Thread10 t10 =new Thread10();
    Thread t101=new Thread(t10, "包子");
    Thread t102=new Thread(t10, "面包");
    t101.start();
    t102.start();
}
/*
运行结果为:
……
包子 num= 24
包子 num= 25
包子 num= 26
包子 num= 27
包子 num= 28
包子 num= 29
包子 num= 30
包子 num= 31
包子 num= 32
包子 num= 33
面包 num= 0
面包 num= 1
面包 num= 2
面包 num= 3
……
面包 num= 30
面包 num= 31
面包 num= 32
面包 num= 33
包子 num= 34
包子 num= 35
包子 num= 36
包子 num= 37
包子 num= 38
……
*/

(As you can see, when the number is 33, all occur Alternate.)

4.wait() and notify() methods:

## Use the two methods together, wait() makes the thread Entering the blocking state, when notify() is called, the thread enters the executable state. You can add or not add parameters in wait(). When adding parameters, the unit is milliseconds. When the specified time is reached or the notify() method is called, it enters the executable state. (Belonging to the Object class, not the Thread class, wait() will first release the locked object, and then perform the waiting action. Since the object waited for by wait() must be locked first, it can only be used for synchronization. program segment or synchronization method, otherwise, an exception IllegalMonitorStateException will be thrown.)


//测试wait()和notify()方法
//用生产者和消费者模式模拟这一过程
/*消费者 */
class Consumer implements Runnable {
private Vector obj;
  public Consumer(Vector v) {
    this.obj = v;
  }
  public void run() {
    synchronized (obj) {
      while (true) {
        try {
          if (obj.size() == 0) {
            obj.wait();
          }
          System.out.println("消费者:我要买面包。");
          System.out.println("面包数: " + obj.size());
          obj.clear();
          obj.notify();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
}
/* 生产者 */
class Producter implements Runnable {
  private Vector obj;
  public Producter(Vector v) {
    this.obj = v;
  }
  public void run() {
    synchronized (obj) {
      while (true) {
        try {
          if (obj.size() != 0) {
            obj.wait();
          }
          obj.add(new String("面包"));
          obj.notify();
          System.out.println("生产者:面包做好了。");
          Thread.sleep(500);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
}
public static void main(String[] args) {
  //测试wait()和notify()
    Vector obj = new Vector();
    Thread consumer = new Thread(new Consumer(obj));
    Thread producter = new Thread(new Producter(obj));
    consumer.start();
    producter.start();
}

5.join() method

Also called thread joining. The current thread A calls the join() method of another thread B. The current thread A enters the blocking state. It is not until thread B finishes running that thread A changes from the blocking state to the executable state.


//测试join
class Thread11 implements Runnable{
  @Override
  public void run() {
    System.out.println("Start Progress.");
    try {
      for(int i=0;i<5;i++){
        System.out.println("Thread11线程 : "+i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("End Progress.");
  }
}
public static void main(String[] args) {
  //测试join
    Thread11 t11=new Thread11();
    Thread t111=new Thread(t11);
    t111.start();
    try {
      t111.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println("hi,I&#39;m Main线程");
}
/*
运行结果为:
Start Progress.
Thread11线程 : 0
Thread11线程 : 1
Thread11线程 : 2
Thread11线程 : 3
Thread11线程 : 4
End Progress.
hi,I&#39;m Main线程
*/

Summary

The above is the detailed content of Sample code for multi-thread blocking and wake-up in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software