线程---同步解决线程的安全问题

class Demo implements Runnable {
    //创建同步所需对象
    Object obj = new Object();
    int num = 100;

    public void run(){
        while(true){
            //创建同步解决线程的安全问题,同步加在使用共享数据的代码快上
            synchronized(obj){
            if(num>0){
                try{Thread.sleep(6);}catch(InterruptedException e){
                    
                }
                System.out.println(Thread.currentThread().getName()+"---"+num);
                num--;
            }
        
            }
        }
    }
}

public class XianCheng {
    public static void main(String[] args) {
        Demo d=new Demo();
        Thread th=new Thread(d);
        Thread th1=new Thread(d);
        Thread th2=new Thread(d);
        th.start();
        th1.start();
        th2.start();
    }
}

两个线程,在两个不同的方法上进行

class Demo implements Runnable {
    int num = 100;
    boolean flag = true;

    public void run() {
        if (flag == true) {
            while (true) {
                synchronized (this) {
                    if (num > 0) {
                        System.out.println(Thread.currentThread().getName() + "---" + num);
                        num--;
                    }

                }
            }
        } else {
            show();
        }
    }

    //当方法里的代码都需要加同步,就可以 在方法上加同步,非静态方法加同步,同步锁使用的是当前对象
    //当在静态方法上加同步时,同步锁是类名加class
    private synchronized void show() {
        // TODO Auto-generated method stub
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "---" + num);
            num--;
        }
    }
}

public class XianCheng {
    public static void main(String[] args) {
        Demo d = new Demo();
        Thread th1 = new Thread(d);
        Thread th2 = new Thread(d);
        th1.start();
        //由于cpu先是在主线程上运行的,当开启第一个线程时cpu不一定立刻执行
        //这时加一个“睡眠”,保证cpu进入第一个线程
        try{Thread.sleep(6);}catch(InterruptedException e){
            
        }
        th2.start();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容