细说Java同步锁(synchronized)

来源:互联网 发布:baocms7.6源码下载 编辑:程序博客网 时间:2024/06/02 02:04

1.如果锁的是对象,同一对象的多个线程并发访问的时候,拿到同步锁的线程会执行临界区的代码,其他线程被阻塞;如果是多个对象的多线程并发就都可以访问;

/** * @author znland * @date 2017年7月27日 12:28:46 * @describe */public class CSDNSynchronized {public void testPrint() {synchronized (this) {int i = 6;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}}public static void main(String[] args) {final CSDNSynchronized csdn = new CSDNSynchronized();Thread test1 = new Thread(new Runnable() {public void run() {csdn.testPrint();}}, "线程1");Thread test2 = new Thread(new Runnable() {public void run() {csdn.testPrint();}}, "线程2");test1.start();test2.start();}}


结果可以看出:一个线程运行时,另一个被阻塞了



2.如果是类锁,这个类的多个实例也是互斥的

/** * @author znland * @date 2017年7月27日 12:28:46 * @describe */public class CSDNSynchronized {/** * 类锁有两种形式的写法 在方法前加上 synchronized static 或 synchronized (*.class),两者功能一致 */public void testPrint() {synchronized (CSDNSynchronized.class) {int i = 6;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}}public synchronized static void testClassPrint() {int i = 6;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}public static void main(String[] args) {final CSDNSynchronized csdn = new CSDNSynchronized();final CSDNSynchronized csdn2 = new CSDNSynchronized();Thread test1 = new Thread(new Runnable() {public void run() {csdn.testPrint();}}, "线程1");Thread test2 = new Thread(new Runnable() {public void run() {csdn2.testPrint();}}, "线程2");test1.start();test2.start();}}


可以看到不同实例的多个线程访问同一个方法时,取得锁的线程执行了临界区代表,另一个线程阻塞了。


3.对象锁和类锁相互不会干扰,也就是同一实例的多个线程访问使用对象锁的方法时,不影响其他线程访问类锁的方法;同理反过来也是一样的。

/** * @author znland * @date 2017年7月27日 12:28:46 * @describe */public class CSDNSynchronized {/** * 类锁有两种形式的写法 在方法前加上 synchronized static 或 synchronized (*.class),两者功能一致 */public void testPrint() {synchronized (this) {int i = 6;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}}public synchronized static void testClassPrint() {int i = 6;while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i);try {Thread.sleep(500);} catch (InterruptedException ie) {}}}public static void main(String[] args) {final CSDNSynchronized csdn = new CSDNSynchronized();Thread test1 = new Thread(new Runnable() {public void run() {csdn.testPrint();}}, "线程1");Thread test2 = new Thread(new Runnable() {public void run() {CSDNSynchronized.testClassPrint();}}, "线程2");test1.start();test2.start();}}



原创粉丝点击