synchronized是Java中的关键字,是一种同步锁。它修饰的对象有如下几种:css
/** * @author shuliangzhao * @Title: SyncThread * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:25 */ public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } @Override public void run() { synchronized (this) { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(syncThread,"Thread1"); Thread thread1 = new Thread(syncThread,"Thread2"); thread.start(); thread1.start(); } }
运行结果java
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:5 Thread2:6 Thread2:7 Thread2:8 Thread2:9
当两个并发线程(thread1和thread2)访问同一个对象(syncThread)中的synchronized代码块时,在同一时刻只能有一个线程获得执行,另外一个线程受阻塞,必须等待当前线程执行完这个代码块之后才能执行该代码块。Thread1和thread2是互斥的,由于在执行synchronized代码块时会锁定当前的对象,只有执行完该代码块才能释放该对象锁,下一个线程才能执行并锁定该对象。数组
把SyncThread的调用稍微改一下:并发
Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start();
运行结果ide
Thread2:0 Thread1:0 Thread1:2 Thread1:3 Thread2:1 Thread2:5 Thread1:4 Thread2:6 Thread1:7 Thread2:8
这时至关于建立了两个SyncThread的对象syncThread1和syncThread2,线程thread1执行的是syncThread1对象中的synchronized代码(run),而线程thread2执行的是syncThread2对象中的synchronized代码(run);咱们知道synchronized锁定的是对象,这时会有两把锁分别锁定syncThread1对象和syncThread2对象,而这两把锁是互不干扰的,不造成互斥,因此两个线程能够同时执行。
b、当一个线程访问对象的一个synchronized(this)同步代码块时,另外一个线程仍然能够访问该对象中的非synchronized(this)同步代码块函数
/** * @author shuliangzhao * @Title: SyncThread1 * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:53 */ public class CountThread implements Runnable{ private static int count; public CountThread() { count = 0; } public void count() { synchronized(this) { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void print() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":count:" + (count)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void run() { String threadName = Thread.currentThread().getName(); if (threadName.equals("A")) { count(); } else if (threadName.equals("B")) { print(); } } public static void main(String[] args) { CountThread countThread = new CountThread(); Thread thread1 = new Thread(countThread, "A"); Thread thread2 = new Thread(countThread, "B"); thread1.start(); thread2.start(); } }
上面代码中count是一个synchronized的,print是非synchronized的。从上面的结果中能够看出一个线程访问一个对象的synchronized代码块时,别的线程能够访问该对象的非synchronized代码块而不受阻塞。
c、指定要给某个对象加锁this
/** * @author shuliangzhao * @Title: Account * @ProjectName design-parent * @Description: TODO * @date 2019/6/18 0:04 */ public class Account { String name; float amount; public Account(String name, float amount) { this.name = name; this.amount = amount; } //存钱 public void deposit(float amt) { amount += amt; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } //取钱 public void withdraw(float amt) { amount -= amt; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } public float getBalance() { return amount; } } /** * 帐户操做类 */ class AccountOperator implements Runnable{ private Account account; public AccountOperator(Account account) { this.account = account; } public void run() { synchronized (account) { account.deposit(500); account.withdraw(500); System.out.println(Thread.currentThread().getName() + ":" + account.getBalance()); } } public static void main(String[] args) { Account account = new Account("zhang san", 10000.0f); AccountOperator accountOperator = new AccountOperator(account); final int THREAD_NUM = 5; Thread threads[] = new Thread[THREAD_NUM]; for (int i = 0; i < THREAD_NUM; i ++) { threads[i] = new Thread(accountOperator, "Thread" + i); threads[i].start(); } } }
运行结果spa
Thread0:10000.0 Thread4:10000.0 Thread3:10000.0 Thread2:10000.0 Thread1:10000.0
在AccountOperator 类中的run方法里,咱们用synchronized 给account对象加了锁。这时,当一个线程访问account对象时,其余试图访问account对象的线程将会阻塞,直到该线程访问account对象结束。也就是说谁拿到那个锁谁就能够运行它所控制的那段代码。
当有一个明确的对象做为锁时,就能够用相似下面这样的方式写程序。线程
public void method3(SomeObject obj) { //obj 锁定的对象 synchronized(obj) { // todo } }
当没有明确的对象做为锁,只是想让一段代码同步时,能够建立一个特殊的对象来充当锁code
private byte[] lock = new byte[0]; // 特殊的instance变量 public void method() { synchronized(lock) { // todo 同步代码块 } } public void run() { }
说明:零长度的byte数组对象建立起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操做码,而Object lock = new Object()则须要7行操做码。
Synchronized修饰一个方法很简单,就是在方法的前面加synchronized,public synchronized void method(){//todo}; synchronized修饰方法和修饰一个代码块相似,只是做用范围不同,修饰代码块是大括号括起来的范围,而修饰方法范围是整个函数。
public synchronized void run() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
Synchronized做用于整个方法的写法。
写法一:
public synchronized void method() { // todo }
写法二:
public void method() { synchronized(this) { // todo } }
在用synchronized修饰方法时要注意如下几点:
class Parent { public synchronized void method() { } } class Child extends Parent { public synchronized void method() { } }
在子类方法中调用父类的同步方法
class Parent { public synchronized void method() { } } class Child extends Parent { public void method() { super.method(); } }
在定义接口方法时不能使用synchronized关键字。
构造方法不能使用synchronized关键字,但可使用synchronized代码块来进行同步
咱们知道静态方法是属于类的而不属于对象的。一样的,synchronized修饰的静态方法锁定的是这个类的全部对象,把SyncThread改造下:
/** * @author shuliangzhao * @Title: SyncThread * @ProjectName design-parent * @Description: TODO * @date 2019/6/17 23:25 */ public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public static void testSync() { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public synchronized void run() { testSync(); } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start(); } }
运行结果
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:0 Thread2:5 Thread2:6 Thread2:7 Thread2:8
syncThread1和syncThread2是SyncThread的两个对象,但在thread1和thread2并发执行时却保持了线程同步。这是由于run中调用了静态方法method,而静态方法是属于类的,因此syncThread1和syncThread2至关于用了同一把锁。
用法
class ClassName { public void method() { synchronized(ClassName.class) { // todo } } }
public class SyncThread implements Runnable { private static int count; public SyncThread() { count = 0; } public static void testSync() { synchronized (SyncThread.class) { try { for (int i = 0;i<5;i++) { System.out.println(Thread.currentThread().getName() + ":" + (count++)); } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public synchronized void run() { testSync(); } public static void main(String[] args) { SyncThread syncThread = new SyncThread(); Thread thread = new Thread(new SyncThread(),"Thread1"); Thread thread1 = new Thread(new SyncThread(),"Thread2"); thread.start(); thread1.start(); } }
运行结果
Thread1:0 Thread1:1 Thread1:2 Thread1:3 Thread1:4 Thread2:5 Thread2:6 Thread2:7 Thread2:8 Thread2:9
A. 不管synchronized关键字加在方法上仍是对象上,若是它做用的对象是非静态的,则它取得的锁是对象;若是synchronized做用的对象是一个静态方法或一个类,则它取得的锁是对类,该类全部的对象同一把锁。B. 每一个对象只有一个锁(lock)与之相关联,谁拿到这个锁谁就能够运行它所控制的那段代码。C. 实现同步是要很大的系统开销做为代价的,甚至可能形成死锁,因此尽可能避免无谓的同步控制。