synchronized (this)同步语句块
1. 一半异步,一半同步
不在synchronized块中是异步执行,在synchronized块中是同步执行
1.1 Task
public class Task {
public void doLongTimeTask(){
//异步执行
for (int i = 0; i < 100000; i++){
System.out.println("not synchronized threadName = " + Thread.currentThread().getName()
+ " i = " + i);
}
System.out.println("=============================");
//同步执行
synchronized (this){
for (int i = 0; i < 100; i++){
System.out.println("synchronized threadName = " + Thread.currentThread().getName()
+ " i = " + i);
}
}
}
}
1.2 ThreadA
public class ThreadA extends Thread {
private Task task;
public ThreadA(Task task){
super();
this.task = task;
}
@Override
public void run(){
super.run();
task.doLongTimeTask();
}
}
1.3 ThreadB
public class ThreadB extends Thread {
private Task task;
public ThreadB(Task task){
super();
this.task = task;
}
@Override
public void run(){
super.run();
task.doLongTimeTask();
}
}
1.4 Test
public class Test {
public static void main(String[] args) {
Task task = new Task();
ThreadA a = new ThreadA(task);
a.start();
ThreadB b = new ThreadB(task);
b.start();
}
}
1.5 运行结果
从执行结果看出不在synchronized块中是异步执行,在synchronized块中是同步执行。
2. synchronized代码块间的同步性
当一个线程访问Object的一个synchronized(this)同步代码块时,其他线程对这个Object的其他synchronized(this)同步代码块(可以不在同一方法中)或者synchronized方法的访问将被阻塞,说明synchronized使用的“对象监视器”是同一个。
2.1 ObjectService
public class ObjectService {
public void serviceMehtodA() {
try {
//线程A调用该代码块,其他的线程也不能调用这个对象的任何synchronized(this)的代码块
synchronized (this) {
System.out.println("A begin");
Thread.sleep(2000);
System.out.println("A end");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void serviceMethodB() {
//只有等到线程A调用完毕,线程B才能调用该synchronized(this)代码块
synchronized (this) {
System.out.println("B begin");
System.out.println("B end");
}
}
//synchronized(this)锁的是对象,所以synchronized方法也会被阻塞
public synchronized void serviceMethodC() {
try {
System.out.println("C begin");
Thread.sleep(500);
System.out.println("C end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.2 ThreadA
public class ThreadA extends Thread {
private ObjectService service;
public ThreadA(ObjectService service){
super();
this.service = service;
}
@Override
public void run(){
super.run();
service.serviceMehtodA();
}
}
2.3 ThreadB
public class ThreadB extends Thread {
private ObjectService service;
public ThreadB(ObjectService service) {
super();
this.service = service;
}
@Override
public void run() {
super.run();
service.serviceMethodB();
}
}
2.4 ThreadC
public class ThreadC extends Thread {
private ObjectService service;
public ThreadC(ObjectService service){
super();
this.service = service;
}
@Override
public void run(){
super.run();
service.serviceMethodC();
}
}
2.5 Test
public class Test {
public static void main(String[] args) {
ObjectService service = new ObjectService();
ThreadA a = new ThreadA(service);
a.start();
ThreadB b = new ThreadB(service);
b.start();
ThreadC c = new ThreadC(service);
c.start();
}
}
2.6 运行结果
A begin
A end
C begin
C end
B begin
B end