JAVA thread synchronization example tutorial

  • 2020-04-01 03:26:39
  • OfStack

Threading is a very important concept in Java programming, and this article explains it in detail in the form of examples. Specific analysis is as follows:

First, what is the use of thread locking? For example: for example, you now have 30000 pieces of ocean deposit in the bank, you take money to the bank now, when you enter a password, after the completion of withdrawal amount has already been entered, your input is 20000, for example, is to give you money in the bank this time, your wife also went to the bank take the money, your wife also take 20000, because now your account is still 30000, so the bank the same operation to your wife side again for a time, so that when the two of you after completion of their respective operating bank records of your account should also have a 10000 yuan deposit, this is good. To solve this problem, we use the knowledge of thread locking. Let's learn it together.

An example of unhandled thread synchronization:


public class TextSync implements Runnable{
  
  Time time = new Time();
  public static void main(String[] args) {
    TextSync text = new TextSync();
    Thread t1 = new Thread(text);
    Thread t2 = new Thread(text);
    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }
  @Override
  public void run() {
    time.add(Thread.currentThread().getName());
  }
}
class Time {
  private static int num = 0;
  public void add(String name){
    try {
      num++;
      //When the first thread executes, num becomes 1, the first thread pauses for a second,
      //The second thread starts executing, and when the second thread finishes, num becomes 2, and the second thread pauses for a second,
      //The num of the first thread also becomes 2, so the final result is 2.
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(name+" Is the first "+num+" Two execution threads. ");
  }
}

Output results:


t2 Is the first 2 Two execution threads. 
t1 Is the first 2 Two execution threads. 

Second, thread synchronization


public class TextSynctwo implements Runnable{
  
  Time1 time = new Time1();
  public static void main(String[] args) {
    TextSynctwo text = new TextSynctwo();
    Thread t1 = new Thread(text);
    Thread t2 = new Thread(text);
    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }
  @Override
  public void run() {
    time.add(Thread.currentThread().getName());
  }
}
class Time1 {
  private static int num = 0;
  
  //Synchronized locks the current thread and can be declared at method definition or set in a method.
  public synchronized void add(String name){
    //synchronized (this) {// Lock the current thread to prevent execution by another thread at this time 
      try {
        num++;
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(name+" Is the first "+num+" Two execution threads. ");
    //}
  }
}

Output results:


t1 Is the first 1 Two execution threads. 
t2 Is the first 2 Two execution threads. 

Third, a deadlock


public class TestDeadLock implements Runnable{
  
  private int flag = 0 ; 
  static Object o1 = new Object();
  static Object o2 = new Object();
  public static void main(String[] args) {
    TestDeadLock td1 = new TestDeadLock(); 
    TestDeadLock td2 = new TestDeadLock(); 
    td1.flag = 1;
    td2.flag = 2;
    Thread t1 = new Thread(td1); 
    Thread t2 = new Thread(td2);
    t1.setName("t1");
    t2.setName("t2");
    t1.start();
    t2.start();
  }

  @Override
  public void run() {
    System.out.println(Thread.currentThread().getName());
    if(flag == 1){
      synchronized(o1){
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized(o2){
          System.out.println("1");
        }
      }
    }
    if(flag == 2){
      synchronized(o2){
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized(o1){
          System.out.println("2");
        }
      }
    }
  }
}

Four, lock


public class TT implements Runnable{
  
  int b = 100;
  public static void main(String[] args) {
    TT tt = new TT();
    Thread th = new Thread(tt);
    th.start();
    try {
      tt.m2();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println(tt.b);
  }
  @Override
  public void run() {
    try {
      m1();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private synchronized void m1() throws Exception{
    b = 1000;
    Thread.sleep(5000);
    System.out.println("b="+b);
  }
  private synchronized void m2() throws Exception{
    Thread.sleep(2500);
    b = 2500;
  } 
}

Now the output is:


1000
b=1000

So you can see that m2 is going to be executed first, and m1 is going to be executed after m2 is executed.

I hope this article has been helpful to your Java programming


Related articles: