1. 程式人生 > >java兩個類的方法同步問題

java兩個類的方法同步問題

fin ring package 業務場景 runnable stub 工作 問題 用戶

  在之前的印象中,只處理過同一個類方法同步的問題。在工作中,遇到了兩個類的方法需要同步的問題。

  具體業務場景是,在某預約系統,預約有兩個入口,一個是pc端的,一個是微信公眾號端的。因為沒有考慮高並發問題,導致兩個用戶同時分別在兩個接口預約導致沖突問題,下面記錄下 ,解決的方法的代碼示例。

  利用一個Thread_C 類做為同步鎖(Thread_C.instance();//單例)

package test;

public class ThreadTest3 {
    /**
     * @param args
     */
    public static
void main(String[] args) { // TODO Auto-generated method stub // 兩個類如何進行同步,使用同一個鎖 Thread_A ta = new Thread_A(); Thread_A ta2 = new Thread_A(); // Thread_B tb = new Thread_B(); Thread t1 = new Thread(ta); Thread t2 = new Thread(ta2);
// Thread t2 = new Thread(tb); t1.start(); t2.start(); } } class Thread_A implements Runnable { Thread_C tca = Thread_C.instance(); public void run() { while (true) { synchronized (tca) { if (Thread_C.num > 0) { System.out.println(
"tca"); try { Thread.sleep(30); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "****tca" + "*****" + Thread_C.num--); } } } } } class Thread_B implements Runnable { Thread_C tcb = Thread_C.instance(); public void run() { while (true) { synchronized (tcb) { if (Thread_C.num > 0) { System.out.println("tcb"); try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "****tcb" + "*****" + Thread_C.num--); } } } } } class Thread_C { private static final Thread_C tc = new Thread_C(); public static int num = 200; private Thread_C() { } public static Thread_C instance() { return tc; } }

java兩個類的方法同步問題