`
standalone
  • 浏览: 611190 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Multithreading in Java (10)

    博客分类:
  • java
阅读更多

Multithreading in Java - Suspending and Resuming Threads


(Page 10 of 10 )

There might be times when you need to temporarily stop a thread from processing and then resume processing, such as when you want to let another thread use the current resource. You can achieve this objective by defining your own suspend and resume methods, as shown in the following example.

This example defines a MyThread class. The MyThread class defines three methods: the run() method, the suspendThread() method, and the resumeThread() method. In addition, the MyThread class declares the instance variable suspended , whose value is used to indicate whether or not the thread is suspended.

The run() method contains a for loop that displays the value of the counter variable. Each time the counter variable is displayed, the thread pauses briefly. It then enters a synchronized statement to determine whether the value of the suspended instance variable is true. If so, the wait() method is called, causing the thread to be suspended until the notify() method is called.

The suspendThread() method simply assigns true to the suspended instance variable. The resumeThread() method assigns false to the suspended instance variable and then calls the notify() method. This causes the thread that is suspended to resume processing.

The main() method of the Demo class declares an instance of MyThread and then pauses for about a second before calling the suspendThread() method and displaying an appropriate message on the screen. It then pauses for about another second before calling the resumeThread() method and again displaying an appropriate message on the screen.

The thread continues to display the value of the counter variable until the thread is suspended. The thread continues to display the value of the counter variable once the thread resumes processing. Here’s what is displayed when you run this program:

Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: Suspended
Thread: Resume
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread exiting.
class MyThread implements Runnable {
  String name;
  Thread t;
  boolean suspended;
  MyThread() {
    
t = new Thread(this, "Thread");
     suspended = false ;
     t.start();
 
}
  public void run() {
     try {
       
for (int i = 0; i < 10; i++) {
           System.out.println("Thread: " + i ); 
           Thread.sleep(200);
           synchronized (this) {
             
while (suspended) {
                 wait();
              }
           }
        }
     } catch (InterruptedException e ) {
         
System.out.println("Thread: interrupted.");
     }
     System.out.println("Thread exiting.");
 
}
  void suspendThread() {
    
suspended = true;
  }
  synchronized void resumeThread() {
    
suspended = false;
     notify();
 
}
}
class Demo {
  
public static void main (String args [] ) {
      MyThread t1 = new MyThread();
      try{
        
Thread.sleep(1000);
         t1.suspendThread();
         System.out.println("Thread: Suspended"); 
         Thread.sleep(1000);
         t1.resumeThread();
         System.out.println("Thread: Resume");
       } catch ( InterruptedException e) {
       }
       try {
         
t1.t.join();
       } catch ( InterruptedException e) {
            System.out.println (
                 "Main Thread: interrupted");
       }
   }
}

Quiz
  1. What is a thread?
  2. What is multitasking?
  3. What kind of overhead occurs during multitasking?
  4. What is a thread priority?
  5. What is synchronization?
  6. What is the Runnable interface ?
  7. When should you extend the Thread class?
  8. If you create one thread in your program, how many threads actually run?
  9. What method must you override when you create a thread in your program?
  10. How do you define the portion of your program that becomes a thread?

分享到:
评论

相关推荐

    《Programming in Java Second Edition》高清完整英文PDF版

    Multithreading in Java Chapter 9. Input/Output, Serialization and Cloning Chapter 10. Generics, java.util and other API Chapter 11. Network Programming Chapter 12. Applets Chapter 13. Event Handling ...

    thinking in Java

    其中,"multithreading applications in Win32.pdf"可能是一个关于Windows平台下多线程应用的补充材料,可能出自另一本书或文章,但与《Thinking in Java》的主题相关。多线程是Java编程中的一个重要部分,它允许...

    1Z0-811 Exam Guide to Have a Cakewalk in Oracle Java SE Certific

    - **Concurrency:** Explore concurrency concepts and multithreading in Java. #### Conclusion The 1Z0-811 exam is a significant step towards achieving Oracle Java SE certification. By following a ...

    Multithreading-in-java

    Java多线程 多线程是Java的一项功能,它允许并发执行程序的两个或更多部分,以最大程度地利用CPU。 这种程序的每个部分都称为线程。 因此,线程是进程中的轻量级进程。 可以使用两种机制来创建线程: 扩展Thread类...

    Java: High-Performance Apps with Java 9

    In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado ever since, working as a Java programmer. In his free time, Nick likes to write and hike in the ...

    Java-Concurrency-Multithreading-in-Practice:Packt出版的《 Java Concurrency&Multithreading in Practice》

    实践中的Java并发和多线程 这是发行的的代码存储库。 它包含从头到尾完成视频课程所需的所有支持项目文件。 关于视频课程 多核处理器无处不在-从超级计算机到随身携带的移动设备。 这就是为什么现代开发人员必须知道...

    A Textbook of Java Programming

    It also discusses about exception handling, multithreading and java libraries. Further, it explains how to interact with client side applications like applets and handling events. The last section ...

    java面试题英文版及其答案

    10. Describe the difference between '==' and `.equals()` in Java.Answer: In Java, '==' is a comparison operator used to compare primitive types, like int or char, and checks if both sides refer to the...

    Java Performance and Scalability

    This book was written with one goal in mind: to provide Java programmers with the expertise needed to build efficient, scalable Java code. The author shares his experience in server-side performance ...

    Java.to.Python 高清完整epub版

    If Java is the heavy metal of computer programming, then Python is the jazz that opens doors of freedom in software development. Both Java and Python are object-oriented programming languages. Both ...

    JAVA核心技术卷一卷二(中文)之part2分卷

    Chapter 7 Exceptions, Logging, Assertions, and Debugging(新增批注共38条) Chapter 8 Generic Programming(新增批注共22条) Chapter 9 Collections(新增批注共55条) Chapter 10 Multithreading(新增批注共...

    Modern Multithreading

    Carver和Kuo-Chung Tai撰写,由John Wiley & Sons, Inc.出版,是一本深入探讨多线程编程的专著,尤其聚焦于Java和C++(包括Pthreads和Win32)语言环境下的多线程程序设计、测试与调试。本书不仅适合初学者作为入门...

    Java - A Beginner’s Guide - Sixth Edition - Herbert Schildt

    This chapter introduces multithreading concepts and techniques in Java, including thread creation, synchronization, and inter-thread communication. Multithreading is particularly useful for improving...

    Thinking_in_Java_4th_Edition_CN

    9. **多线程(Multithreading)**:Java支持多线程编程,书中会讲解线程的创建、同步和通信,以及线程池的使用。 10. **输入/输出流(I/O Stream)**:介绍如何在Java中进行文件读写,网络通信以及其他类型的输入...

    Core Java. Volume I. Fundamentals, 8th Edition JAVA核心技术1基础知识

    3 FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA 4 OBJECTS AND CLASSES 5 INHERITANCE 6 INTERFACES AND INNER CLASSES 7 GRAPHICS PROGRAMMING 8 EVENT HANDLING 9 USER INTERFACE COMPONENTS WITH SWING 10 ...

    Core.Java.B013WZRDNQ

    Core Java offers a total immersion approach for CC++ programmer wanting to learn...Chapter 10 Multithreading Chapter 11 Exception Handling Chapter 12 Applet Chapter 13 Managing Input/Output Files in Java

    producer_consumer_using_multithreading_in_java:用Java实现的经典生产者消费者问题的多线程解决方案

    6. ** 示例代码 **:在`producer_consumer_using_multithreading_in_java-master`这个项目中,应该包含了一个完整的示例,演示了如何用Java实现生产者消费者模型。源代码可能包括一个`Producer`类和一个`Consumer`类...

    JAVA核心技术卷一卷二(中文)之part4分卷

    Chapter 7 Exceptions, Logging, Assertions, and Debugging(新增批注共38条) Chapter 8 Generic Programming(新增批注共22条) Chapter 9 Collections(新增批注共55条) Chapter 10 Multithreading(新增批注共...

Global site tag (gtag.js) - Google Analytics