This program uses a synchronized block. : synchronized « Thread « Java Tutorial

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Thread » synchronized 
10.11.4.This program uses a synchronized block.Previous/Next
class Callme {
  void call(String msg) {
    System.out.print("[" + msg);
    try {
      Thread.sleep(1000);
    catch (InterruptedException e) {
      System.out.println("Interrupted");
    }
    System.out.println("]");
  }
}

class Caller implements Runnable {
  String msg;

  Callme target;

  Thread t;

  public Caller(Callme targ, String s) {
    target = targ;
    msg = s;
    t = new Thread(this);
    t.start();
  }

  public void run() {
    synchronized (target) { // synchronized block
      target.call(msg);
    }
  }
}

class Synch1 {
  public static void main(String args[]) {
    Callme target = new Callme();
    Caller ob1 = new Caller(target, "Hello");
    Caller ob2 = new Caller(target, "Synchronized");
    Caller ob3 = new Caller(target, "World");

    try {
      ob1.t.join();
      ob2.t.join();
      ob3.t.join();
    catch (InterruptedException e) {
      System.out.println("Interrupted");
    }
  }
}
10.11.synchronized
10.11.1.Test Synchronized method
10.11.2.Test Unsynchronized method
10.11.3.This program is not synchronized.
10.11.4.This program uses a synchronized block.
10.11.5.Flag Communication
10.11.6.Waiting on an object
10.11.7.wait() and notify() must only be issued inside a synchronized block
10.11.8.guarantee that threads are woken in the same order in which they waited
10.11.9.creating a piped communications system between two threads.
10.11.10.Handle concurrent read/write: use synchronized to lock the data
10.11.11.A synchronized collection with Collections.synchronizedCollection
10.11.12.Determining If the Current Thread Is Holding a Synchronized Lock
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.