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

Multithreading in Java (9)

    博客分类:
  • java
阅读更多

Multithreading in Java - Using the Synchronized Statement


(Page 9 of 10 )

Synchronizing a method is the best way to restrict the use of a method one thread at a time. However, there will be occasions when you won’t be able to synchronize a method, such as when you use a class that is provided to you by a third party. In such cases, you don’t have access to the definition of the class, which prevents you from using the synchronized keyword.

An alternative to using the synchronized keyword is to use the synchronized statement. A synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized. Calls to the methods contained in the synchronized block happen only after the thread enters the monitor of the object.

Although you can call methods within a synchronized block, the method declaration must be made outside a synchronized block.

The following example shows how to use a synchronized statement. This is basically the same as the previous example; however, the synchronized statement is used instead of the synchronized keyword. The synchronized statement is placed in the run() method within the MyThread class. The synchronized statement synchronizes the instance of the Parentheses class and thus prevents two threads from calling the display() method concurrently.

class Parentheses  {
   void display(String s) {
   System.out.print ("(" + s);
   try {
     
Thread.sleep (1000);
   } catch (InterruptedException e) {
       
System.out.println ("Interrupted");
   }
   System.out.println(")");
 
}
}
class MyThread implements Runnable {
  
String s1;
  
Parentheses p1;
   Thread t;
   public MyThread (Parentheses p2, String s2) {
     
p1= p2;
      s1= s2;
      t = new Thread(this);
      t.start();
  
}
   public void run() {
       synchronized(p1){
          p1.display(s1);
       }
  
}
}
class Demo{
  
public static void main (String args[]) {
     Parentheses p3 = new Parentheses();
     MyThread name1 = new MyThread(p3, "Bob");
     MyThread name2 = new MyThread(p3, "Mary");
     try {
       
name1.t.join();
        name2.t.join();
     } catch (InterruptedException e ) {
          System.out.println( "Interrupted");
     }
  }
}

Here, the display() method is not modified by synchronized . Instead, the synchronized statement is used inside the caller’s run() method. This causes the same correct output as before, because each thread waits for the prior one to finish before proceeding.

Communicating Between Threads

Threads have opened programmers to a new dimension in programming, where parts of a program can execute asynchronously, each processing independently of the other. However, sometimes threads have to coordinate their processing and therefore need to be able to communicate with each other during processing. Programmers call this interprocess communication .

You can have threads communicate with each other in your program by using the wait(), notify() , and notifyAll() methods. These methods are called from within a synchronized method. The wait() method tells a thread to relinquish a monitor and go into suspension. There are two forms of the wait() method. One form doesn’t require an argument and causes a thread to wait until it is notified. The other form of the wait() method let’s you specify the amount of time to wait. You specify the length of time in milliseconds, which is passed to the wait() method.

The notify() method tells a thread that is suspended by the wait() method to wake up again and regain control of the monitor. The notifyAll() method wakes up all threads that are waiting for control of the monitor. Only the thread with the highest priority is given control over the monitor. The other threads wait in suspension until the monitor becomes available again.

The following example shows you how to use these methods in an application. The objective of the program is to have the Publisher class give a value to the Consumer class through the use of a Queue class. The Publisher class places a value on the queues and then waits until the Consumer class retrieves the value before the Publisher class places another value on the queue.

This example defines four classes: the Queue class, the Publisher class, the Consumer class, and the Demo class. The Queue class defines two instance values: exchangeValue and a flag. The exchangeValue is used to store the value placed on the queue by the publisher. The flag variable is used as a sign indicating whether a value has been placed on the queue. This is set to false by default, which enables the producer to place a value on to the queue. The Queue class also defines a get() method and a put() method. The put() method is used to place a value on to the queue (that is, to assign a value to the exchangeValue variables). The get() method is used to retrieve the value contained on the queue (that is, to return the value of exchangeValue ). Once the value is assigned, the put() method changes the value of the flag from false to true, indicating there is a value on the queue. Notice how the value of the flag is used within the get() method and the put() method to have the thread that calls the method wait until either there is a value on the queue or there isn’t a value on the queue, depending on which method is being called.

The Publisher class declares an instance of the Queue class and then calls the put() method to place five integers on the queue. Although the put() method is called within a for loop, each integer is placed on the queue and then there is a pause until the integer is retrieved by the Consumer class.

The Consumer class is very similar in design to the Publisher class, except the Consumer class calls the get() method five times from within a for loop. Each call to the get() method is paused until the Publisher class places an integer in the queue.

The main() method of the Demo class creates instances of the Queue class, the Publisher class, and the Consumer class. Notice that both constructors of the Publisher class and the Consumer class are passed a reference to the instance of the same Queue class. They use the instance of the Queue class for inter-process communication .

Here’s what you see when you run this program. Notice that the value placed on the queue by the Publisher is retrieved by the Consumer before the Publisher places the next value on the queue.

Put: 0
Get: 0
Put: 1
Get: 1
Put: 2
Get: 2
Put: 3
Get: 3
Put: 4
Get: 4
class Queue {
  
int exchangeValue;
    boolean busy = false;
    synchronized int get() {
      
if (!busy)
          try {
             wait();
          } catch (InterruptedException e) {
               System.out.println(
                   "Get: InterruptedException");
          }
        System.out.println("Get: " + exchangeValue);
         notify();
      
return exchangeValue;
    }
    synchronized void put (int exchangeValue) {
      
if (busy)
          try {
             wait();
          } catch (InterruptedException e) {
               System.out.println(
                    "Put: InterruptedException");
          }
       this.exchangeValue = exchangeValue;
      
busy = true;
       System.out.println("Put: " + exchangeValue);
       notify();
   
}
}
class Publisher implements Runnable {
  
Queue q;
  
Publisher(Queue q) {
      this.q = q;
      new Thread (this, "Publisher").start();
  
}
   public void run() {
      for (int i = 0; i < 5; i++){
         q.put(i);
      }
  
}
}
class Consumer implements Runnable {
  
Queue  q;
  
Consumer (Queue  q) {
      this.q = q;
      new Thread (this, "Consumer").start();
  
}
   public void run() {
      for (int i = 0; i < 5; i++){
         q.get();
      }
  
}
}
class Demo {
  
public static void main(String args []) {
     Queue q = new Queue ();
     new Publisher (q);
     new Consumer (q);
  
}
}


NOTE:    If your program seems to hang when using two or more threads, you should suspect that a deadlock has occurred. A deadlock occurs when all threads in contention for a resource wait, thinking that another thread is using the resource when actually no thread is using it. Look for code where two threads access two synchronized objects. They could be doing this in an unusual sequence. Redesign your program to avoid this situation. A deadlock can also occur in a rare time-slicing sequence, where the operating system causes a circular dependency of two threads.

分享到:
评论

相关推荐

    《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 ...

    Java: High-Performance Apps with Java 9

    Build microservices in Java 9 Implement APIs to improve application code Authors Mayur Ramgir Mayur Ramgir has more than 16 years of experience in the software industry, working at various levels. He ...

    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-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 ...

    Core Java 9th Edition(Vol1,Vol2)

    Fundamental Programming Structures in Java Chapter 4. Objects and Classes Chapter 5. Inheritance Chapter 6. Interfaces and Inner Classes Chapter 7. Graphics Programming Chapter 8. Event Handling ...

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

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

    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面试题英文版及其答案

    9. What are the access modifiers in Java, and what do they control?Answer: Java provides four access modifiers: public, protected, private, and default (no modifier specified). These control 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 ...

    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 java. The course will use JDK(Java Development Kit) and covers all the ...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`类...

Global site tag (gtag.js) - Google Analytics