zoukankan      html  css  js  c++  java
  • Java_锁Synchronized

    
    
    锁(synchronized):
    既然线程之间是并发执行,就必然会有资源冲突的时候,如果不加以限制,很可能会出现死锁现象,这时就需要锁来对线程获取资源的限制
    程序中,可以给类,方法,代码块加锁。
    1.方法锁,也叫对象锁:synchronized修饰方法
    package com.lan.lock;
    public class SThread implements Runnable{
        private static int count=0;
    @Override
    public synchronized void run() {
    System.out.println("111111");
    for (int i = 0; i < 5; i++) {
    System.out.println(Thread.currentThread().getName() + ":" + count++);
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    
    
    package com.lan.lock;
    public class SClass {
    public static void main(String[] args) {
    
    
       SThread st = new SThread();
    new Thread(st, "t1").start();
    new Thread(st,"t2").start();
    
    
        }
    }
    synchronized修饰方法,即对象锁,如果同一个对象的多个线程访问该方法是就会同步,比如上面的t1、t2是同一个对象st的两个线程,
    当他们访问到run()方法时,先访问方法的对象拿到后就会对该方法上锁,后面的对象只有等前一个释放该锁才能继续执行。
    
    
    2.代码块锁:synchronized修饰代码块,用this关键字修饰代码块
    
    
    package com.lan.lock;

    public class SThread implements Runnable{
    private static int count=0;
    @Override
    public void run() {
    System.out.println("111111");
    synchronized (this) {
    for (int i = 0; i < 5; i++) {
    System.out.println(Thread.currentThread().getName() + ":" + count++);
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
    
    
    synchronized修饰this代码块也属于对象锁,当对象访问到该this代码块时就会被同步,锁代码块很大程度上减小了锁的范围,降低对象等待的时间

    3.类锁:synchronized 修饰static方法变类锁

    形式1:
    private static synchronized void method1(){
    
    
            try {
    
    
    
    
    
    
                System.out.println(Thread.currentThread().getName());
    
    
    
    
    
    
                Thread.sleep(4000);
    
    
    
    
    
    
            } catch (InterruptedException e) {
    
    
                 e.printStackTrace();
    
    
             }
    
    
       }
    
    
    形式2:
    public class SThread implements Runnable{
        private static int count=0;
    @Override
    public void run() {
    System.out.println("111111");
    synchronized (SThread.class) { //类锁,修饰静态方法
    for (int i = 0; i < 5; i++) {
    System.out.println(Thread.currentThread().getName() + ":" + count++);
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    }
    }
    如果synchironized修饰了静态方法,那么该方法就属于类锁,类锁是锁住整个类,这时无论多少个对象,多少个线程访问该方法都会被锁同步。
     
  • 相关阅读:
    Python基础综合练习
    熟悉常用的Linux操作
    大数据概述
    C语言简易文法(无左递归)
    自动机
    C语言简易文法
    词法分析实验报告
    词法分析
    综合练习:词频统计
    组合数据类型综合练习
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10627417.html
Copyright © 2011-2022 走看看