1、概念理解:
2、同步的解决方案:
1).基于代码
synchronized 关键字
修饰普通方法:作用于当前实例加锁,进入同步代码前要获得当前实例的锁。
修饰静态方法:作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁。
修饰代码块:指定加锁对象,对给定对象加锁,进入同步代码块前要获得给定对象的锁。
code1
package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 同步方法 * @author Administrator * */ public class SynchronizedMethod implements Runnable{ //静态共享变量 i static int i = 0; /** * 自增 */ public synchronized void increase(){ i++; } @Override public void run() { for (int j = 0; j < 100; j++) { increase(); } } public static void main(String[] args) throws InterruptedException { SynchronizedMethod instance = new SynchronizedMethod(); ExecutorService executorService = Executors.newFixedThreadPool(2); for (int i = 0; i < 3; i++) { //同一实例,线程共享静态变量i // executorService.execute(instance); //不同实例,线程单独享有变量i,达不到同步目的 executorService.execute(new SynchronizedMethod()); /** * 由于线程执行时间过短,在不同实例下,可能会得到类似于同步的结果。 */ Thread.sleep(100); } executorService.shutdown(); System.out.println(i); //300 } }
code2
package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 同步代码块 * @author Administrator * */ public class SynchronizedCodeBlock implements Runnable{ //静态共享变量 i static int i = 0; @Override public void run() { //同步进来的对象 synchronized(this){ //SynchronizedCodeBlock.class for (int j = 0; j < 100; j++) { i++; } } } public static void main(String[] args) throws InterruptedException { SynchronizedCodeBlock instance = new SynchronizedCodeBlock(); ExecutorService executorService = Executors.newFixedThreadPool(2); for (int i = 0; i < 3; i++) { // executorService.execute(instance); executorService.execute(new SynchronizedCodeBlock()); Thread.sleep(10); } executorService.shutdown(); System.out.println(i); //300 } }
参考博客:
https://blog.csdn.net/javazejian/article/details/72828483
2).基于数据库
原文地址:https://www.cnblogs.com/x-jingxin/p/10250482.html
时间: 2024-11-04 02:54:38