java thread synchronization

java thread synchronization

Without thread synchronization:

 TestSync.java

/*
	Thread synchronization:
	synchronized
*/
public class TestSync implements Runnable {
  //Timer as parameter
  Timer timer = new Timer ();
  public static void main(String[] args) {
    TestSync test = new TestSync();
    Thread t1 = new Thread(test);
    Thread t2 = new Thread(test);
    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }
  public void run(){
	//name of the current thread
    timer.add(Thread.currentThread().getName());
  }
}

class Timer{
  private static int num = 0;
  // During the execution of the method, the current object is locked
  public /*synchronized*/ void add(String name){
	//locking
  	//synchronized (this) {
	    num++;
	    try {Thread.sleep(1);}
	    catch (InterruptedException e) {}
	    System.out.println(name+", you are the "+num+" thread using timer");
	  //}
  }
}

 

F:\java\Thread>javac TestSync.java

F:\java\Thread>java TestSync
t1, you are the second thread using timer
t2, you are the second thread using timer

F:\java\Thread>

 

Use thread synchronization

TestSync.java

/*
	Thread synchronization:
	synchronized
*/
public class TestSync implements Runnable {
  //Timer as parameter
  Timer timer = new Timer ();
  public static void main(String[] args) {
    TestSync test = new TestSync();
    Thread t1 = new Thread(test);
    Thread t2 = new Thread(test);
    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }
  public void run(){
	//name of the current thread
    timer.add(Thread.currentThread().getName());
  }
}

class Timer{
  private static int num = 0;
  // During the execution of the method, the current object is locked
  public synchronized void add(String name){
	//locking
  	//synchronized (this) {
	    num++;
	    try {Thread.sleep(1);}
	    catch (InterruptedException e) {}
	    System.out.println(name+", you are the "+num+" thread using timer");
	  //}
  }
}

 

F:\java\Thread>javac TestSync.java

F:\java\Thread>java TestSync
t2, you are the first thread to use timer
t1, you are the second thread using timer

F:\java\Thread>

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327070416&siteId=291194637