2017-02-27 29 views
0

我在web應用程序中使用spring boot和mysql。與spreed同步的方法

此應用程序用tomcat

我需要生成誰就會在數據庫中插入一個值。

我想避免在同一時間有多個花費誰訪問方法。

我想知道如果使用同步與春天是爲這個問題去的方式。

+2

請添加代碼來了解您的要求。 –

+0

當你擁有Spring和數據庫時,'synchronized'幾乎是不可能的。你想要交易。 – john16384

回答

0

您可以使用synchronized methodsynchronized block with single or multiple monitor lock來實現此目的。但是,還有其他方法,如:ExecutorService,Countdown latch, Producer-consumer approach etc。我建議你做一些研究並選擇你認爲有說服力的適當方法。

至於同步方法是關注,在這裏,我已經證明的情況下兩個線程調用的常用方法增量()和常用的方法試圖改變共享數據線程間計數器

public class App { 

// this is a shared data between two threads. 
private int counter = 0; 


//this method is invoked from both threads. 
private synchronized void increment() { 
    counter++; 
} 

public static void main(String[] args) { 
    App app = new App(); 
    app.doWork(); 
} 


private void doWork() { 

    Thread thread1 = new Thread(() -> { 
     for (int i = 0; i < 10000; i++) { 
      increment(); 
     } 
    }); 

    Thread thread2 = new Thread(() -> { 
     for (int i = 0; i < 10000; i++) { 
      increment(); 
     } 
    }); 

    thread1.start(); 
    thread2.start(); 


    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(" The counter is :" + counter); 
    //output shoud be equal to : 20000 
    } 
} 

現在,嘗試從該方法中除去increment()關鍵字​​,重新編譯代碼並看到輸出的性質它產生。