Java线程同步的一些例子
2023-09-14 09:03:08 时间
例1 - synchronized和volatile
package volatileTest;
public class VolatileTest01 {
volatile
int i;
// synchronized if commented out, sum will not equal to 1000
// synchronized 注释了synchronized,即使加上volatile也得不到1000的结果
public void addI(){
i++;
}
public static void main(String[] args) throws InterruptedException {
final VolatileTest01 test01 = new VolatileTest01();
for (int n = 0; n < 1000; n++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
test01.addI();
}
}).start();
}
Thread.sleep(10000);//等待10秒,保证上面程序执行完成
System.out.println(test01.i);
}
}
缓存一致性协议——Intel 的MESI协议,保证了每个缓存中使用的共享变量的副本是一致的。它核心的思想是:当CPU写数据时,如果发现操作的变量是共享变量,即在其他CPU中也存在该变量的副本,会发出信号通知其他CPU将该变量的缓存行置为无效状态,因此当其他CPU需要读取这个变量时,发现自己缓存中缓存该变量的缓存行是无效的,那么它就会从内存重新读取。
例2 - CountDownLatch
package threadTest2;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest {
private static final int COUNT = 10;
// 每一个线程减一次1
private static class TestRunnable implements Runnable {
private final CountDownLatch countDownLatch;
private byte[] lock;
TestRunnable(CountDownLatch countDownLatch, byte[] byteArray) {
this.countDownLatch = countDownLatch;
this.lock = byteArray;
}
@Override
public void run() {
synchronized(this.lock) {
System.out.println("Thread id: " + Thread.currentThread().getId());
countDownLatch.countDown();
System.out.println("Left number: " + countDownLatch.getCount());
if( countDownLatch.getCount() == 0){
System.out.println("!!!!!!!!!! Game over!!!!!!!!!!!");
}
}
}
}
public void testThreadPool() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(COUNT);
ExecutorService executorService = Executors.newFixedThreadPool(10);
long bg = System.currentTimeMillis();
final byte[] lock = new byte[0]; // 特殊的instance变量
for (int i = 0; i < COUNT; i++) {
Runnable command = new TestRunnable(countDownLatch, lock);
executorService.execute(command);
}
countDownLatch.await();
System.out.println("testThreadPool:"
+ (System.currentTimeMillis() - bg));
}
public void testNewThread() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(COUNT);
long bg = System.currentTimeMillis();
final byte[] lock = new byte[0]; // 特殊的instance变量
for (int i = 0; i < COUNT; i++) {
Runnable command = new TestRunnable(countDownLatch, lock);
Thread thread = new Thread(command);
thread.start();
}
countDownLatch.await();
System.out
.println("testNewThread:" + (System.currentTimeMillis() - bg));
}
public static void main(String[] arg) {
ThreadPoolTest a = new ThreadPoolTest();
try {
// a.testThreadPool();
a.testNewThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
Thread id: 13
Left number: 9
Thread id: 22
Left number: 8
Thread id: 21
Left number: 7
Thread id: 20
Left number: 6
Thread id: 19
Left number: 5
Thread id: 17
Left number: 4
Thread id: 16
Left number: 3
Thread id: 18
Left number: 2
Thread id: 15
Left number: 1
Thread id: 14
Left number: 0
testNewThread:8
!!! Game over!!!
例3 - 一个死锁的例子
package thread;
public class DeadLockExample {
public static void main(String[] args) {
final String resource1 = "ABAP";
final String resource2 = "Java";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(100);
} catch (Exception e) {
}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try {
Thread.sleep(100);
} catch (Exception e) {
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
相关文章
- Java面试问题总结带答案(多线程)
- java queue toarray_Java PriorityBlockingQueue toArray()用法及代码示例
- java对象组声明_如何在Java中声明对象数组?
- java打印数组_Java中打印数组的三种方式
- java反转数组_Java实现数组反转翻转的方法实例
- Java并发——线程同步Volatile与Synchronized详解
- java语言的平台无关性是指什么,《深入Java虚拟机》学习笔记二:平台无关性
- java图书馆新地址_最受Java开发者喜爱的5款开源IDE盘点
- java环境_Java 开发环境配置
- MySQL字段类型如何转为java_Java JDBC中,MySQL字段类型到JAVA类型的转换
- java 生成xml dom4j_Java生成xml——DOM4J生成
- 浅析Java多态_JAVA多态
- java创建线程池的几种方式_Java中的线程池
- 大数据必学Java基础(一百一十七):三个案例开发
- java多线程有几种实现方法线程之间如何同步详解编程语言
- Java学习笔记之十三初探Java面向对象的过程及代码实现详解编程语言
- net.sf.json.JSONException: java.lang.reflect.InvocationTargetException & java.lang.NullPointerExcept详解编程语言
- java 线程之对象的同步和异步详解编程语言
- 应用『Java应用程序中Redis缓存的使用』(redis缓存与java)
- Java介绍,基础入门
- Java连接MySQL:实现数据库操作(java中连接mysql)
- 使用Java连接MySQL数据库的具体操作方法(java连接mysql代码)
- MySQL与Java整合:新的操作模式初现(javamysql操作)
- Java存入Oracle数据库实现快速高效的数据存储(java存入oracle)
- Java实现Redis队列锁功能(redis队列锁java)
- java获得指定日期的前一天,后一天的代码
- JAVA生产者消费者(线程同步)代码学习示例
- java实现非法访问异常示例