为了避免临界区静态条件的发生,可以使用阻塞时的解决方案:synchronized,即俗称的对象锁,
它采用互斥的方式让同一时刻至多只有一个线程能持有对象锁。
注意
虽然java中互斥和同步都可以采用synchronized关键字来完成,但它们还是有区别的
互斥是同一时刻只能有一个线程执行执行临界区代码。
同步时由于线程执行的先后,顺序不同,需要一个线程等待其它线程运行到某个点。
//synchronized加在对象上
package hello;
import java.util.*;
public class Main{
public static void main(String[] args) throws InterruptedException{
Test t=new Test();
Thread t1=new Thread(()->{
for(int i=0;i<500;i++) {
t.increase();
}
});
Thread t2=new Thread(()->{
for(int i=0;i<500;i++) {
t.decrease();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(t.getCount());
}
}
class Test{
private static int count=0;
public void increase() {
synchronized(this) {
count++;
}
}
public void decrease() {
synchronized(this) {
count--;
}
}
public int getCount() {
return count;
}
}
//synchronized加载非静态方法上
//public synchronized void test(){
//}等价于
//public void test(){
// synchronized(this){
//}
//}
package hello;
import java.util.*;
public class Main{
public static void main(String[] args) throws InterruptedException{
Test t=new Test();
Thread t1=new Thread(()->{
for(int i=0;i<500;i++) {
t.increase();
}
});
Thread t2=new Thread(()->{
for(int i=0;i<500;i++) {
t.decrease();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(t.getCount());
}
}
class Test{
private static int count=0;
public synchronized void increase() {
count++;
}
public synchronized void decrease() {
count--;
}
public int getCount() {
return count;
}
}
//synchronized加在静态方法上相当于锁住了类对象
//public synchronized static void test(){
//
//}等价于
//public static void test(){
// synchronized(Test.class){
//
//}
//}