Home > Java > Java Tutorial > body text

Java Example - Thread hangs

黄舟
Release: 2016-12-27 13:36:58
Original
1721 people have browsed it

The following example demonstrates how to suspend a thread:

/*
 author by w3cschool.cc
 SleepingThread.java
 */public class SleepingThread extends Thread {
   private int countDown = 5;
   private static int threadCount = 0;
   public SleepingThread() {
      super("" + ++threadCount);
      start();
   }
   public String toString() { 
      return "#" + getName() + ": " + countDown;
   }
   public void run() {
      while (true) {
         System.out.println(this);
         if (--countDown == 0)
            return;
         try {
            sleep(100);
         }
         catch (InterruptedException e) {
            throw new RuntimeException(e);
         }
      }
   }
   public static void main(String[] args) 
   throws InterruptedException {
      for (int i = 0; i < 5; i++)
      new SleepingThread().join();
      System.out.println("线程已被挂起");
   }}
Copy after login

The output result of running the above code is:

#1: 5
#1: 4
#1: 3
#1: 2
#1: 1
……
#5: 3
#5: 2
#5: 1
线程已被挂起
Copy after login

The above is the Java example - the content of thread suspension, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!