1.当多个线程同时修改一个变量。造成线程不安全
public class ThreadSafe {
int count=0;
public void increase(){
count++;
}
public void decrease() {
count--;
}
public static void main(String[] args) throws InterruptedException {
ThreadSafe threadSafe=new ThreadSafe();
Thread thread1=new Thread(()->{
for (int i=0;i<1000;i++){
threadSafe.increase();
}
});
Thread thread2=new Thread(()->{
for (int i=0;i<1000;i++){
threadSafe.decrease();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(threadSafe.count);//结果不为0
}
}
2.解决上面的线程安全问题——使用 Synchronized
//修饰普通方法
public class Synchronized {
int count=0;
synchronized void increase(){
count++;
}
synchronized void decrease(){
count--;
}
public static void main(String[] args) throws InterruptedException {
Synchronized thread=new Synchronized();
Thread thread1=new Thread(()->{
for (int i=0;i<1000;i++){
thread.increase();
}
});
Thread thread2=new Thread(()->{
for (int i=0;i<1000;i++){
thread.decrease();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(thread.count);//结果为0
}
}
//修饰静态方法
public class Synchronized {
static int count=0;
synchronized static void increase(){
count++;
}
synchronized static void decrease(){
count--;
}
public static void main(String[] args) throws InterruptedException {
Synchronized thread=new Synchronized();
Thread thread1=new Thread(()->{
for (int i=0;i<1000;i++){
thread.increase();
}
});
Thread thread2=new Thread(()->{
for (int i=0;i<1000;i++){
thread.decrease();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(thread.count);//结果为0
}
}
//修饰代码块——synchronized ()
//1.上锁的必须为同一个对象,要为都为类:(类名.class);要为都为对象:(this);要为都为自定义的锁对象
public class Synchronized {
Object object=new Object();// 2.synchronized也可自定义锁对象,将下面Synchronized(this)换成Synchronized(object)也可以,
int count=0;
void increase(){//普通方法
synchronized (this){ //3.注意synchronized (this)不可用在静态方法中
count++;
}
}
void decrease(){
synchronized (this){
count--;
}
}
public static void main(String[] args) throws InterruptedException {
Synchronized thread=new Synchronized();
Thread thread1=new Thread(()->{
for (int i=0;i<1000;i++){
thread.increase();
}
});
Thread thread2=new Thread(()->{
for (int i=0;i<1000;i++){
thread.decrease();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(thread.count);//结果为0
}
}
synchronized 也可以保证的内存可见性https://blog.youkuaiyun.com/xhhhx_/article/details/124128387