synchronized的使用

在编写一个类时,如果该类中的代码可能运行于多线程环境下,那么就要考虑同步的问题。在Java中内置了语言级的同步原语--synchronized,这也大大简化了Java中多线程同步的使用。

直接上代码

package com.crm.learn.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestThread {

	public static CountDownLatch count = new CountDownLatch(2);

	public static Object o = new Object();
	public static Long numx = new Long(0l);

	public static void main(String[] args) {
		Lock mainLock = new ReentrantLock();
		try {
			VThread v1 = new VThread(1000000, mainLock);
			VThread v2 = new VThread(2000000, mainLock);
			
			v1.start();
			v2.start();
			count.await();
			System.out.println(numx);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

线程类

package com.crm.learn.thread;

import java.util.concurrent.locks.Lock;

public class VThread extends Thread {

	private long addNum = 0;
	private Lock mainLock;

	public VThread(long addNum, Lock mainLock) {
		this.addNum = addNum;
		this.mainLock = mainLock;
	}

	public void run() {
		try {
			for (int i = 0; i < addNum; i++) {
				try {
					//如果锁定numx,数量 != 3000000
//					synchronized (TestThread.numx) {
//						TestThread.numx++;
//					}
					
					//如果锁定o,数量 =3000000
//					synchronized (TestThread.o) {
//						TestThread.numx++;
//					}
					
					//如果锁定TestThread.class,数量 =3000000
//					synchronized (TestThread.class) {
//						TestThread.numx++;
//					}
					
					//使用锁对象,数量 =3000000
//					mainLock.lock();
//					TestThread.numx++;
//					mainLock.unlock();
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			TestThread.count.countDown();
		}
	}
}

 

 

为啥

synchronized (TestThread.numx) {

TestThread.numx++;

 

}

这个值不为3000000

你可能感兴趣的:(synchronized的使用)