其他分享
首页 > 其他分享> > 利用变量来实现线程间的同步

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

作者:互联网

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

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;
    }
}
ysphello0 发布了28 篇原创文章 · 获赞 14 · 访问量 2万+ 私信 关注

标签:同步,java,变量,isstop,Thread,static,import,线程,public
来源: https://blog.csdn.net/qq_28738419/article/details/104063615