目录
synchronized 是 Java 中的关键字,是一种同步锁。主要应用于多线程环境下保证线程的安全性。
被修饰的代码块称为同步语句块,其作用的范围是大括号{} 括起来的代码,作用的对象是调用这个代码块的对象;
被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象;
虽然可以使用 synchronized 来定义方法,但 synchronized 并不属于方法定义的一部分,因此,synchronized 关键字不能被继承。如果在父类中的某个方 法使用了 synchronized 关键字,而在子类中覆盖了这个方法,在子类中的这 个方法默认情况下并不是同步的,而必须显式地在子类的这个方法中加上 synchronized 关键字才可以。当然,还可以在子类方法中调用父类中相应的方 法,这样虽然子类中的方法不是同步的,但子类调用了父类的同步方法,因此, 子类的方法也就相当于同步了。
其作用的范围是整个静态方法,作用的对象是这个类的 所有对象;
其作用的范围是synchronized后面括号括起来的部分,作用对象是这个类的所有对象。
1) 一个线程访问一个对象中的synchronized(this)同步代码块时,其他试图访问该对象的线程将被阻塞。
- class SyncThread implements Runnable {
- private static int count;
-
- public SyncThread() {
- count = 0;
- }
-
- public void run() {
- 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 int getCount() {
- return count;
- }
- }
-
- public class SynchronizedDemo {
- public static void main(String args[]){
- //test01
- // SyncThread s1 = new SyncThread();
- // SyncThread s2 = new SyncThread();
- // Thread t1 = new Thread(s1);
- // Thread t2 = new Thread(s2);
- //test02
- SyncThread s = new SyncThread();
- Thread t1 = new Thread(s);
- Thread t2 = new Thread(s);
-
- t1.start();
- t2.start();
- }
- }
Test01

test02

从运行结果test02可以看出当两个并发线程(thread1和thread2)访问同一个对象(syncThread)中的synchronized代码块时,在同一时刻只能有一个线程得到执行,另一个线程受阻塞,必须等待当前线程执行完这个代码块以后才能执行该代码块。Thread1和thread2是互斥的,因为在执行synchronized代码块时会锁定当前的对象,只有执行完该代码块才能释放该对象锁,下一个线程才能执行并锁定该对象
为什么上面的例子中thread1和thread2同时在执行。这是因为synchronized只锁定对象,每个对象只有一个锁(lock)与之相关联。
2)当一个线程访问对象的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该对象中的非synchronized(this)同步代码块。(作业:自行验证)
3)指定要给某个对象加锁
- package CompleteFuture;
-
-
- /**
- * 银行账户类
- */
- 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 class SynchDemo2 {
- //public static final Object signal = new Object(); // 线程间通信变量
- //将account改为Demo00.signal也能实现线程同步
- 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();
- }
- }
- }

在AccountOperator 类中的run方法里,我们用synchronized 给account对象加了锁。这时,当一个线程访问account对象时,其他试图访问account对象的线程将会阻塞,直到该线程访问account对象结束。也就是说谁拿到那个锁谁就可以运行它所控制的那段代码。
3.3 .1当有一个明确的对象作为锁时,就可以用类似下面这样的方式写程序。
- public void method3(SomeObject obj)
- {
- //obj 锁定的对象
- synchronized(obj)
- {
- // todo
- }
- }
3.3.2 当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的对象来充当锁:
- class Test implements Runnable
- {
- private byte[] lock = new byte[0]; // 特殊的instance变量
- public void method()
- {
- synchronized(lock) {
- // todo 同步代码块
- }
- }
-
- public void run() {
-
- }
- }
- 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(); }
- }
- /**
- * 同步线程
- */
- class SyncThread implements Runnable {
- private static int count;
-
- public SyncThread() {
- count = 0;
- }
-
- public synchronized static void method() {
- for (int i = 0; i < 5; i ++) {
- try {
- System.out.println(Thread.currentThread().getName() + ":" + (count++));
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public synchronized void run() {
- method();
- }
- }
-
- public class Demo00{
-
- public static void main(String args[]){
- SyncThread syncThread1 = new SyncThread();
- SyncThread syncThread2 = new SyncThread();
- Thread t1 = new Thread(syncThread1, "SyncThread1");
- Thread t2 = new Thread(syncThread2, "SyncThread2");
- t1.start();
- t2.start();
- }
- }

syncThread1和syncThread2是SyncThread的两个对象,但在t1和t2并发执行时却保持了线程同步。这是因为run中调用了静态方法method,而静态方法是属于类的,所以syncThread1和syncThread2相当于用了同一把锁。
其作用的范围是synchronized后面括号括起来的部分,作用对象是这个类的所有对象。
- /**
- * 同步线程
- */
- class SyncThread implements Runnable {
- private static int count;
-
- public SyncThread() {
- count = 0;
- }
-
- public static void method() {
- synchronized(SyncThread.class) {
- for (int i = 0; i < 5; i ++) {
- try {
- System.out.println(Thread.currentThread().getName() + ":" + (count++));
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- public synchronized void run() {
- method();
- }
- }
消费者与生产者
- package CompleteFuture;
-
- import java.util.Random;
-
- public class ProducerAndConsumer {
- public static void main(String[] args) {
-
- //多线程如何编写
- // 1、线程操作资源类
- // 2、创建资源类 ,在资源类中创建属性和操作资源方法
- Product product = new Product();
- for (int i = 1; i < 10; i++) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- product.product();
- }
- },"生产者: "+i).start();
- }
-
-
- for (int i = 1; i <10; i++) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- product.consume();
- }
- },"消费者: "+i).start();
- }
- }
-
- }
-
- // 资源类
- class Product{
-
- private volatile int num = 0;
-
- public synchronized void product(){
-
- // 1、馒头有的多我就可以不生产
- while (num !=0){
-
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- // 一次生产五个
- for (int i = 0; i <5 ; i++) {
- ++num;
- }
-
- // 产生了馒头通知消费者
- this.notifyAll();
- System.out.println(Thread.currentThread().getName()+"生产后剩余馒头:"+num);
-
- }
-
-
- public synchronized void consume(){
-
- // 1、如果没有馒头我就等待,阻塞消费
- while (num == 0){
-
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- // 一次吃2个
- for (int i = 0; i < 2; i++) {
- if(num>0) {
- --num;
- }
- }
-
- // 模拟消耗馒头1s
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- this.notifyAll();
- System.out.println(Thread.currentThread().getName()+"消费后剩余馒头:"+num);
- }
- }
单例模式(双重检测):
A. 无论synchronized关键字加在方法上还是对象上,如果它作用的对象是非静态的,则它取得的锁是对象;如果synchronized作用的对象是一个静态方法或一个类,则它取得的锁是对类,该类所有的对象同一把锁。
B. 每个对象只有一个锁(lock)与之相关联,谁拿到这个锁谁就可以运行它所控制的那段代码。
C. 实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。
本文主要整理的是synchronized主要用法,但它实际的原理没有进行详细的拆解。且看下回剖析。