JAVA多线程编程核心技术--synchronized关键词
这个是书当中的例子
synchronized关键词
特性
- 可重入
锁this对象
- Service.java
package com.service;
public class Service {
public void sayA() throws InterruptedException {
\t//注意,new String()和 = “”是不同的概念
String anyString = new String();
synchronized (anyString){
System.out.println("线程名称为"+ Thread.currentThread().getName()+"在"+ System.currentTimeMillis()+ " 进入同步快");
Thread.sleep(2000);
System.out.println("线程名称为"+ Thread.currentThread().getName()+"在"+ System.currentTimeMillis()+ " 离开同步快");
}
}
public void sayB() throws InterruptedException {
synchronized(this){
System.out.println("线程名称为"+ Thread.currentThread().getName()+"在"+ System.currentTimeMillis()+ " 进入同步块");
Thread.sleep(2000);
System.out.println("线程名称为"+ Thread.currentThread().getName()+"在"+ System.currentTimeMillis()+ " 离开同步块");
}
}
}
- ThreadA.java
package com.service;
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service){
this.service = service;
}
@Override
public void run() {
try {
service.sayA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- ThreadB.java
ppackage com.service;
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service){
this.service = service;
}
@Override
public void run() {
try {
service.sayB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- Run.java
package com.service;
public class Run {
public static void main(String[] args) {
Service service = new Service();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
}
}
运行结果
线程名称为A在1572859726886 进入同步快
线程名称为B在1572859726887 进入同步块
线程名称为A在1572859728887 离开同步快
线程名称为B在1572859728888 离开同步块
Process finished with exit code 0
结果
this对象锁与string锁是异步的
锁class和static方法
- synchronized(this) 锁的该类的实例对象--
局部锁
- synchronized(Service.class) 锁的是class类--
全局锁
- 如果synchronized修饰的是静态方法,代表了用的class锁
public class Service {
public synchronized static int getValue(){
return 1;
}
}