Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 同步方法与spreed_Java_Mysql_Spring - Fatal编程技术网

Java 同步方法与spreed

Java 同步方法与spreed,java,mysql,spring,Java,Mysql,Spring,我在web应用程序中使用spring boot和mysql 此应用程序使用tomcat 我需要生成一个将插入数据库的值 我希望避免同时使用多个访问方法 我想知道对spring使用synchronized是否是解决此问题的方法。您可以使用synchronized method或带有单个或多个监视器锁的同步块来实现此目的。但是,也有其他方法,比如:ExecutorService、倒计时闩锁、生产者-消费者方法等。我建议您做一些研究,选择您认为有说服力的适当方法 至于synchronized方法,这里

我在web应用程序中使用spring boot和mysql

此应用程序使用tomcat

我需要生成一个将插入数据库的值

我希望避免同时使用多个访问方法


我想知道对spring使用synchronized是否是解决此问题的方法。

您可以使用
synchronized method
或带有单个或多个监视器锁的
同步块来实现此目的。但是,也有其他方法,比如:
ExecutorService、倒计时闩锁、生产者-消费者方法等。我建议您做一些研究,选择您认为有说服力的适当方法

至于synchronized方法,这里我演示了一种情况,其中两个线程调用一个公共方法increment(),该公共方法尝试更改线程之间的共享数据计数器

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
  }
}
公共类应用程序{
//这是两个线程之间的共享数据。
专用整数计数器=0;
//此方法从两个线程调用。
私有同步的void增量(){
计数器++;
}
公共静态void main(字符串[]args){
App App=新App();
app.doWork();
}
私房{
线程线程1=新线程(()->{
对于(int i=0;i<10000;i++){
增量();
}
});
线程线程2=新线程(()->{
对于(int i=0;i<10000;i++){
增量();
}
});
thread1.start();
thread2.start();
试一试{
睡眠(1000);
}捕捉(中断异常e){
e、 printStackTrace();
}
System.out.println(“计数器为:“+计数器”);
//产量应等于:20000
}
}

现在,尝试从方法
increment()
中删除关键字
synchronized
,重新编译代码并查看它产生的输出的性质。

请添加代码以了解您的需求。
synchronized
在您有Spring和数据库的情况下几乎从来都不是一种方法。你想要交易。