前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java线程同步的一些例子

Java线程同步的一些例子

作者头像
Jerry Wang
发布2020-05-04 13:45:43
4450
发布2020-05-04 13:45:43
举报

例1 - synchronized和volatile

代码语言:javascript
复制
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

代码语言:javascript
复制
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 - 一个死锁的例子

代码语言:javascript
复制
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();
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 例1 - synchronized和volatile
  • 例2 - CountDownLatch
  • 例3 - 一个死锁的例子
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档