并发线程在访问 synchronized(this) 同步代码块时,一段时间内只能有一个线程被执行,另一个线程必须等待当前线程执行完这个代码块后才能执行;
示例代码:
Task.java
package com.daimakuai;
/**
* @Auther: 13213
* @Date: 2020/5/30 17:59
* @Description:
*/
public class Task {
public void doLongTimeTask(){
for (int i = 0; i < 100; i++) {
System.out.println("nosynchronized threadName="+Thread.currentThread().getName()+" i="+(i+1));
}
System.out.println("============================");
synchronized (this){
for (int i = 0; i < 100; i++) {
System.out.println("synchronized threadName="+Thread.currentThread().getName()+" i="+(i+1));
}
}
}
}
MyThreadA.java
package com.daimakuai;
/**
* @Auther: 13213
* @Date: 2020/5/30 18:03
* @Description:
*/
public class MyThreadA extends Thread{
private Task task;
public MyThreadA(Task task) {
super();
this.task = task;
}
@Override
public void run(){
super.run();
task.doLongTimeTask();
}
}
MyThreadB.java
package com.daimakuai;
/**
* @Auther: 13213
* @Date: 2020/5/30 21:11
* @Description:
*/
public class MyThreadB extends Thread{
private Task task;
public MyThreadB(Task task) {
super();
this.task = task;
}
@Override
public void run(){
super.run();
task.doLongTimeTask();
}
}
Test.java
package com.daimakuai;
/**
* @Auther: 13213
* @Date: 2020/5/30 21:12
* @Description:
*/
public class Test {
public static void main(String[] args) {
Task task = new Task();
MyThreadA a = new MyThreadA(task);
a.start();
MyThreadB b = new MyThreadB(task);
b.start();
}
}