Java线程同步的一些例子
生活随笔
收集整理的這篇文章主要介紹了
Java线程同步的一些例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
例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() {@Overridepublic 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;// 每一個線程減一次1private static class TestRunnable implements Runnable {private final CountDownLatch countDownLatch;private byte[] lock;TestRunnable(CountDownLatch countDownLatch, byte[] byteArray) {this.countDownLatch = countDownLatch;this.lock = byteArray;}@Overridepublic 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 resource2Thread 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线程同步的一些例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据ABAP类方法的形式参数名,反查是哪
- 下一篇: 暴走英雄坛怎么上吊