从头认识java-18.6 synchronized在其他对象上同步和ThreadLocal来消除共享对象的同步问题

这一章节我们来介绍在其他对象上同步与ThreadLocal。

前一章节我们使用了

1.synchronized在其他对象上同步

class ThreadA implements Runnable {
	private Object object = new Object();

	private synchronized void test() throws InterruptedException {
		System.out.println("dosomething");
		Thread.sleep(5000);
		synchronized (object) {
			System.out.println("dosomething");
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				test();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}


2.ThreadLocal来消除共享对象的同步问题

package com.ray.ch18;

public class Test {

	public static void main(String[] args) {
		new Thread(new Accessor(new ThreadLocalVarHoder())).start();
		new Thread(new Accessor(new ThreadLocalVarHoder())).start();
		new Thread(new Accessor(new ThreadLocalVarHoder())).start();
	}
}

class Accessor implements Runnable {
	private ThreadLocalVarHoder threadLocalVarHoder;

	public Accessor(ThreadLocalVarHoder threadLocalVarHoder) {
		this.threadLocalVarHoder = threadLocalVarHoder;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			threadLocalVarHoder.increment();
			System.out.println(Thread.currentThread().getName() + " "
					+ threadLocalVarHoder.get());
		}
	}

}

class ThreadLocalVarHoder {
	private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
		protected Integer initialValue() {
			return 0;
		}
	};

	public void increment() {
		value.set(value.get() + 1);
	}

	public int get() {
		return value.get();
	}
}

输出:

Thread-0 1
Thread-0 2
Thread-0 3
Thread-1 1
Thread-2 1
Thread-2 2
Thread-2 3
Thread-1 2
Thread-1 3


从上面的输出可以看见,每一个线程都是读取自己线程上面的副本的值,它的修改这些不涉及原来的对象。


总结:这一章节简单介绍了synchronized在其他对象上同步和ThreadLocal来消除共享对象的同步问题。


这一章节就到这里,谢谢。

-----------------------------------

目录


你可能感兴趣的:(java)