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

Multithreading in Java (8)

    博客分类:
  • java
阅读更多

Multithreading in Java - Synchronizing Threads


(Page 8 of 10 )

A major concern when two or more threads share the same resource is that only one of them can access the resource at one time. Programmers address this concern by synchronizing threads, much the same way baseball players take turns being up to bat.

Threads are synchronized in Java through the use of a monitor. Think of a monitor as an object that enables a thread to access a resource. Only one thread can use a monitor at any one time period. Programmers say that the thread owns the monitor for that period of time. The monitor is also called a semaphore .

A thread can own a monitor only if no other thread owns the monitor. If the monitor is available, a thread can own the monitor and have exclusive access to the resource associated with the monitor. If the monitor is not available, the thread is suspended until the monitor becomes available. Programmers say that the thread is waiting for the monitor.

Fortunately, the task of acquiring a monitor for a resource happens behind the scenes in Java. Java handles all the details for you. You do have to synchronize the threads you create in your program if more than one thread will use the same resource.

You have two ways in which you can synchronize threads: You can use the synchronized method or the synchronized statement.

The Synchronized Method

All objects in Java have a monitor. A thread enters a monitor whenever a method modified by the keyword synchronized is called. The thread that is first to call the synchronized method is said to be inside the method and therefore owns the method and resources used by the method. Another thread that calls the synchronized method is suspended until the first thread relinquishes the synchronized method.

If a synchronized method is an instance method, the synchronized method activates the lock associated with the instance that called the synchronized method, which is the object known as this during the execution of the body of the method. If the synchronized method is static, it activates the lock associated with the class object that defines the synchronized method.

Before you learn how to define a synchronized method in your program, let’s see what might happen if synchronization is not used in a program. This is the objective of the following example. This program displays two names within parentheses using two threads. This is a three-step process, where the opening parenthesis, the name, and the closing parenthesis are displayed in separate steps.

The example defines three classes: the Parentheses class, the MyThread class, and the Demo class, which is the program class. The Parentheses class defines one method called display(), which receives a string in its argument list and displays the string in parentheses on the screen. The MyThread class defines a thread. In doing so, the constructor of MyThread requires two arguments. The first argument is a reference to an instance of the Parentheses class. The second argument is a string containing the name that will be displayed on the screen. The run() method uses the instance of the Parentheses class to call its display() method, passing the display() method the name that is to appear on the screen.

The rest of the action happens in the main() method of the Demo class. The first statement declares an instance of the Parentheses class. The next two classes create two threads. Notice that both threads use the same instance of the Parentheses class.

Here’s what is displayed when you run this program. It’s probably not what you expected to see. Each name should be enclosed within its own parentheses. The problem is that the display() method isn’t synchronized.


NOTE:    If a variable is assigned by one thread and is used or assigned by other threads, all access to the variable should be enclosed in a synchronized method or a synchronized statement.

  (Bob(Mary)
)
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() {
     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");
     }
  }
}

The problem with the previous example is that two threads use the same resource concurrently. The resource is the display() method defined in the Parentheses class. In order to have one thread take control of the display() method, we must synchronize the display() method. This is done by using the keyword synchronized in the header of the display() method, which is illustrated in the next example.

Here’s what is displayed when you run the next example. This is what you expected to see in the previous example.

(Bob)
(Mary)
class Parentheses {
   synchronized 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() {
     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");
   }
  }
}

分享到:
评论

相关推荐

    《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-Concurrency-Multithreading-in-Practice:Packt出版的《 Java Concurrency&Multithreading in Practice》

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

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

    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核心技术卷一卷二(中文)之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面试题英文版及其答案

    8. Explain the concept of encapsulation in OOP and how it is achieved in Java.Answer: Encapsulation is a fundamental principle of Object-Oriented Programming (OOP) that involves bundling data and ...

    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)语言环境下的多线程程序设计、测试与调试。本书不仅适合初学者作为入门...

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

    代码示例请到此地址下载:【corejava8代码示例】http://download.csdn.net/source/2366281 1 AN INTRODUCTION TO JAVA Java As a Programming Platform The Java “White Paper” Buzzwords Simple Object Oriented...

    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中进行文件读写,网络通信以及其他类型的输入...

    OReilly Java Cookbook 3rd Edition

    If you are familiar with Java basics, this cookbook will bolster your knowledge of the language in general and Java 8’s main APIs in particular. Recipes include: Methods for compiling, running, ...

    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

    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