Test Unsynchronized method : synchronized « Thread « Java Tutorial






public class TestUnsynchronized {
  int taskID;

  public void doAction(int val) {
    print("entering doAction()");
    taskID = val;
    print("doAction() taskID " + taskID);
    try {
      Thread.sleep(4000);
    } catch (InterruptedException x) {
    }
    print("doAction() sleep after taskID " + taskID);
    print("leaving performATask()");
  }

  public static void print(String msg) {
    String threadName = Thread.currentThread().getName();
    System.out.println(threadName + ": " + msg);
  }

  public static void main(String[] args) throws Exception {
    final TestUnsynchronized tus = new TestUnsynchronized();

    Runnable runA = new Runnable() {
      public void run() {
        tus.doAction(3);
      }
    };

    Thread ta = new Thread(runA, "threadA");
    ta.start();

    Thread.sleep(2000);

    Runnable runB = new Runnable() {
      public void run() {
        tus.doAction(7);
      }
    };

    Thread tb = new Thread(runB, "threadB");
    tb.start();
  }
}








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