zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java线程同步的一些例子

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();
	}
}