利用变量来实现线程间的同步

以下代码无法同步,没有锁住读写变量

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class SynLock {
    public static boolean isstop;

    public static void main(String[] args) throws InterruptedException{
        System.out.println(isstop);
        Thread background = new Thread(()->{
            int i=0;
            while (!isstop){
                i++;
            }
        });
        background.start();
        TimeUnit.SECONDS.sleep(1);
        isstop=true;
    }
}

以下代码锁住变量的读写

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class SynLock {
    public   static boolean isstop;

    //写锁
    public synchronized  static void set(){
        isstop=true;
    }
    //读锁
    public synchronized static boolean read(){
        return isstop;
    }

    public static void main(String[] args) throws InterruptedException{
        System.out.println(isstop);
        Thread background = new Thread(()->{
            int i=0;
            while (!read()){
                i++;
            }
        });
        background.start();
        TimeUnit.SECONDS.sleep(1);
        set();
    }
}

给变量名称增加修饰符 volatile 也能起到同样的作用

import java.sql.Time;
import java.util.concurrent.TimeUnit;

public class SynLock {
    public static  volatile boolean isstop;

    public static void main(String[] args) throws InterruptedException{
        System.out.println(isstop);
        Thread background = new Thread(()->{
            int i=0;
            while (!isstop){
                i++;
            }
        });
        background.start();
        TimeUnit.SECONDS.sleep(1);
        isstop=true;
    }
}

你可能感兴趣的:(线程)