在之前的印象中,只处理过同一个类方法同步的问题。在工作中,遇到了两个类的方法需要同步的问题。
具体业务场景是,在某预约系统,预约有两个入口,一个是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; } }