synchronized作为java并发编程最重要的知识点之一,用法大致可以分为两点,对象(object)锁与类(class)锁,各自又可以再细分为代码块锁与方法锁。本文主要对这四种情况的基本用法进行整理。
对象-代码块锁
public class SynchronizedObjectCodeBlock implements Runnable {
static SynchronizedObjectCodeBlock instance = new SynchronizedObjectCodeBlock();
public static void main(String[] args) {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
while(t1.isAlive() || t2.isAlive()){
}
System.out.println("finished");
}
@Override
public void run() {
synchronized (this) {
System.out.println("object的代码块锁,线程:" + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "运行结束。");
}
}
}
对象-方法锁
public class SynchronzizedObjectMethod implements Runnable{
static SynchronzizedObjectMethod instance = new SynchronzizedObjectMethod();
public static void main(String[] args){
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
while(t1.isAlive() || t2.isAlive()){
}
System.out.println("finished");
}
@Override
public void run() {
method();
}
public synchronized void method(){
System.out.println("对象锁的方法锁,线程:"+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "运行结束");
}
}
类-代码块
public class SynchronizedClassClass implements Runnable{
static SynchronizedClassClass instance1 = new SynchronizedClassClass();
static SynchronizedClassClass instance2 = new SynchronizedClassClass();
public static void main(String[] args){
Thread t1 = new Thread(instance1);
Thread t2 = new Thread(instance2);
t1.start();
t2.start();
while(t1.isAlive() || t2.isAlive()){}
System.out.println("finished");
}
public void method(){
synchronized (SynchronizedClassClass.class){
System.out.println("类锁的:*.class形式。线程:" + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "运行结束");
}
}
@Override
public void run() {
method();
}
}
类-方法锁:
public class SychronizedClassStatic implements Runnable{
static SychronizedClassStatic instance1 = new SychronizedClassStatic();
static SychronizedClassStatic instance2 = new SychronizedClassStatic();
public static void main(String[] args){
Thread t1 = new Thread(instance1);
Thread t2 = new Thread(instance2);
t1.start();
t2.start();
while(t1.isAlive() || t2.isAlive()){}
System.out.println("finished");
}
public static synchronized void method(){
System.out.println("类锁的static方法形式。线程:"+ Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行结束");
}
@Override
public void run() {
method();
}
}
本文参考慕课网课程《Java高并发之魂:synchronized深度解析》
https://www.imooc.com/learn/1086
网友评论