线程安全与非线程安全

1、线程不共享数据
对同一资源,各个线程各自执行一遍,代码如下:

package com.zzm.th01;

/**
 * 线程不共享数据
 * Created by ming on 2017/6/15.
 */
public class th04 extends Thread{
    //记录资源总数
    private int count = 4;
    @Override
   public void run() {
        super.run();
        count--;
        System.out.println(Thread.currentThread().getName()+"执行->"+count);
    }

    public static void main(String[] args) {
        th04 th = new th04();
        th04 th1 = new th04();
        th04 th2 = new th04();
        th.start();
        th1.start();
        th2.start();
    }
}

2、线程数据共享
这种情况会有非线程安全问题。需要加synchronized。代码如下:

package com.zzm.th01;

/**
 * Created by ming on 2017/6/15.
 */
public class th05 extends Thread {
    int count = 7;
    @Override
  synchronized   public void run() {
        super.run();
        count--;
        System.out.println(Thread.currentThread().getName()+"执行->"+count);
    }

    public static void main(String[] args) {
        th05 th = new th05();
        Thread th1 = new Thread(th,"线程1");
        Thread th2 = new Thread(th,"线程2");
        Thread th3 = new Thread(th,"线程3");

        th1.start();
        th2.start();
        th3.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值