多线程学习Day02--加餐

根本停不下来

变量的线程安全分析

成员变量和静态变量是否线程安全?
   如果它们没有共享,则线程安全
   如果它们被共享了,根据它们的状态是否能够改变,又分两种情况
   如果只有读操作,则线程安全
   如果有读写操作,则这段代码是临界区,需要考虑线程安全(按我个人的理解,共享+写就涉及到线程安全问题了)

局部变量是否线程安全?
   局部变量是线程安全的
   但局部变量引用的对象则未必
   如果该对象没有逃离方法的作用访问,它是线程安全的
   如果该对象逃离方法的作用范围,需要考虑线程安全

局部变量线程安全分析

局部变量 i,会在每个线程的栈帧内存中被创建多份,因此不存在共享,没有共享就没有伤害

                               

class ThreadUnsafe {
ArrayList<String> list = new ArrayList<>();
public void method1(int loopNumber) {
for (int i = 0; i < loopNumber; i++) {
// { 临界区, 会产生竞态条件
method2();
method3();
// } 临界区
}
}
private void method2() {
list.add("1");
}
private void method3() {
list.remove(0);
}
}
static final int THREAD_NUMBER = 2;
static final int LOOP_NUMBER = 200;
public static void main(String[] args) {
ThreadUnsafe test = new ThreadUnsafe();
for (int i = 0; i < THREAD_NUMBER; i++) {
new Thread(() -> {
test.method1(LOOP_NUMBER);
}, "Thread" + i).start();
}
}

其中一种情况是,如果线程2 还未 add,线程1 remove 就会报错,这很好理解

list改成局部变量,直接拿下

class ThreadSafe {
public final void method1(int loopNumber) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < loopNumber; i++) {
method2(list);
method3(list);
}
}
private void method2(ArrayList<String> list) {
list.add("1");
}
private void method3(ArrayList<String> list) {
list.remove(0);
}
}

如果子类重写一下方法就可能会有问题,这里又多了一个线程,如果不想子类影响,可以加一个final修饰符,或者权限控制变成private。

class ThreadSafeSubClass extends ThreadSafe{
@Override
public void method3(ArrayList<String> list) {
new Thread(() -> {
list.remove(0);
}).start();
}
}

常见线程安全类

String、Integer、StringBuffer、Random、Vector、Hashtable、java.util.concerrent包下的类,多个线程调用他们的同一个实例的方法时,线程是安全的。他们的每个方法时原子性的。但是如果多个方法组合在一起就不是原子的了。

一个简单的小例子

Hashtable table = new Hashtable();
// 线程1,线程2
if( table.get("key") == null) {
table.put("key", value);
}
不可变类线程安全性

String和Integer等都是不可变类,其内部的状态不可改变,所以线程安全(被共享了也安全)。

实例分析

例1

public class MyServlet extends HttpServlet {
    // 是否安全?  当然不是
    Map<String,Object> map = new HashMap<>();
    // 是否安全?  yes
    String S1 = "...";
    // 是否安全?  yes
    final String S2 = "...";
    // 是否安全?  不安全呢
    Date D1 = new Date();
    // 是否安全?  注意这个也不行,对象里面的属性可能会被修改
    final Date D2 = new Date();
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        // 使用上述变量
    }
}

例2

public class MyServlet extends HttpServlet {
     // 是否安全?  不安全
     private UserService userService = new UserServiceImpl();
     public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
}
}
public class UserServiceImpl implements UserService {
     // 记录调用次数
     private int count = 0;
     public void update() {
     //这就像是临界区了
     count++;
}
}

例3

@Aspect
@Component
public class MyAspect {
    // 是否安全?  不安全,成员变量可能会被并发修改
    private long start = 0L;
    @Before("execution(* *(..))")
    public void before() {
        start = System.nanoTime();
    }
    @After("execution(* *(..))")
    public void after() {
        long end = System.nanoTime();
        System.out.println("cost time:" + (end-start));
    }
}

例4

public class MyServlet extends HttpServlet {
    // 是否安全  安全
    private UserService userService = new UserServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}
public class UserServiceImpl implements UserService {
    // 是否安全 安全,它没有成员变量
    private UserDao userDao = new UserDaoImpl();
    public void update() {
        userDao.update();
    }
}
public class UserDaoImpl implements UserDao {
    public void update() {
        String sql = "update user set password = ? where username = ?";
// 是否安全   安全,这是局部变量
        try (Connection conn = DriverManager.getConnection("","","")){
// ...
        } catch (Exception e) {
// ...
        }
    }
}

例5

public class MyServlet extends HttpServlet {
    // 是否安全 安全
    private UserService userService = new UserServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}
public class UserServiceImpl implements UserService {
    // 是否安全  安全
    private UserDao userDao = new UserDaoImpl();
    public void update() {
        userDao.update();
    }
}
public class UserDaoImpl implements UserDao {
    // 是否安全 不安全,这个要组成线程私有的局部变量
    private Connection conn = null;
    public void update() throws SQLException {
        String sql = "update user set password = ? where username = ?";
        conn = DriverManager.getConnection("","","");
// ...
        conn.close();
    }
}

例6

public class MyServlet extends HttpServlet {
    // 是否安全 安全
    private UserService userService = new UserServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}
public class UserServiceImpl implements UserService {
    public void update() {
        UserDao userDao = new UserDaoImpl();
        userDao.update();
    }
}
public class UserDaoImpl implements UserDao {
// 是否安全 安全但是不推荐
    private Connection = null;
    public void update() throws SQLException {
        String sql = "update user set password = ? where username = ?";
        conn = DriverManager.getConnection("","","");
// ...
        conn.close();
    }
}

例7

public abstract class Test {
    public void bar() {
// 是否安全 不安全,局部变量也要看引用是否泄露
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        foo(sdf);
    }
    public abstract foo(SimpleDateFormat sdf);
    public static void main(String[] args) {
        new Test().bar();
    }
}
public void foo(SimpleDateFormat sdf) {
    String dateStr = "1999-10-11 00:00:00";
    for (int i = 0; i < 20; i++) {
        new Thread(() -> {
        try {
        sdf.parse(dateStr);
        } catch (ParseException e) {
        e.printStackTrace();
  }
  }).start();
  }
  } 
卖票的练习
@Slf4j(topic = "c.sellTicket")
public class sellTicket {
    public static void main(String[] args) {
        //模拟多人买票
        TicketWindow ticketWindow = new TicketWindow(4000);
        List<Thread> list = new ArrayList<>();
        // 用来存储买出去多少张票
        List<Integer> sellCount = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread t = new Thread(() -> {
                // 分析这里的竞态条件
                int count = ticketWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        //使得所有线程都能结束,之后再统计
        list.forEach((t) -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
       // 买出去的票求和
        log.debug("卖出去的票数:{}",sellCount.stream().mapToInt(c -> c).sum());
       // 剩余票数
        log.debug("剩余票数:{}", ticketWindow.getCount());
    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}
class TicketWindow {
    private int count;
    public TicketWindow(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }
    public int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}

经我实现,这是存在线程安全问题的,但是真得执行好多次才能出现这个结果

20:41:56 [main] c.sellTicket - 卖出去的票数:4001
20:41:56 [main] c.sellTicket - 剩余票数:0

加锁拿下,感觉分析有点难啊

class TicketWindow {
    private int count;
    public TicketWindow(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}
转账练习
@Slf4j(topic = "c.ExerciseTransfer")
public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        log.debug("total:{}",(a.getMoney() + b.getMoney()));
    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~100
    public static int randomAmount() {
        return random.nextInt(100) +1;
    }
}
class Account {
    private int money;
    public Account(int money) {
        this.money = money;
    }
    public int getMoney() {
        return money;
    }
    public void setMoney(int money) {
        this.money = money;
    }
    //这里共享变量有两个this.getMoney()和target.getMoney(),只加synchronized时不行的
    public  void transfer(Account target, int amount) {
            if (this.money > amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
    }
}

这个有点难搞

20:59:31 [main] c.ExerciseTransfer - total:5082

直接把类锁上

class Account {
    private int money;
    public Account(int money) {
        this.money = money;
    }
    public int getMoney() {
        return money;
    }
    public void setMoney(int money) {
        this.money = money;
    }
    //这里共享变量有两个this.getMoney()和target.getMoney(),只加synchronized时不行的
    public  void transfer(Account target, int amount) {
            synchronized (Account.class){
                if (this.money > amount) {
                    this.setMoney(this.getMoney() - amount);
                    target.setMoney(target.getMoney() + amount);
                }
            }
    }
}

打完收工

  • 16
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值