sysnchronized:同步锁,依赖于jvm实现,在作用对象的作用范围内同一时刻只能有一个线程来操作。
不可中断锁,适合竞争不激烈,可读性好
修饰代码块:{}之间的代码,作用于调用的代码块的对象
修饰方法:整个方法,作用于调用的方法的对象
修饰静态方法:整个静态方法,作用于所有对象
修饰类:括号括起来的部分,作用于所有对象
package com.jiaoshou.concurency.example.sysc;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author yangkaifei
* @date 2018/12/5 11:44
*/
@Slf4j
public class SynchronizedExample{
/******修饰一个代码块*******/
public void test1(){
synchronized (this){
for (int i =0; i <10; i++) {
log.info("test1-{}",i);
}
}
}
/*******修饰一个方法*******/
public synchronized void test2(String sss){
for (int i =0; i <10; i++) {
log.info("test2-{} {}",sss,i);
}
}
/******修饰一个类*******/
public static void test1(){
synchronized (SynchronizedExample2.class){
for (int i = 0; i < 10; i++) {
log.info("test1-{}",i);
}
}
}
/*******修饰一个静态方法*******/
public static synchronized void test2(String sss){
for (int i = 0; i < 10; i++) {
log.info("test2-{} {}",sss,i);
}
}
public void test(String sss){
for (int i =0; i <10; i++) {
log.info(sss+"-{}",i);
}
}
public static void main(String[] args) {
SynchronizedExample syn1=new SynchronizedExample();
SynchronizedExample syn2=new SynchronizedExample();
//声明一个线程池
ExecutorService executorService=Executors.newCachedThreadPool();
executorService.execute(
()->{syn1.test2("aaa");}
);
executorService.execute(
()->{syn2.test2("bbb");}
);
}
}
lock:依赖于cpu执行(ReentrantLock)
可中断锁,多样化同步,竞争激烈时能维持常态。
都撒旦法