鱼C论坛

 找回密码
 立即注册
查看: 2334|回复: 1

多线程上锁问题

[复制链接]
发表于 2022-7-18 16:05:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. public class Homework02 {
  2.     public static void main(String[] args) {
  3.         User user = new User();

  4.         Thread thread1 = new Thread(user);
  5.         thread1.setName("t1");
  6.         Thread thread2= new Thread(user);
  7.         thread2.setName("t2");

  8.         thread1.start();
  9.         thread2.start();
  10.     }
  11. }

  12. class User implements Runnable {
  13.     private boolean loop = true;
  14.     private int total = 10000;

  15.     @Override
  16.     public void run() {
  17.         while (loop) {

  18.             synchronized (this) {
  19.                 if (total < 1000) {
  20.                     System.out.println("余额不足1000");
  21.                     break;
  22.                 }

  23.                 total -= 1000;
  24.                 System.out.println(Thread.currentThread().getName() + "取走一千块钱" + "  余额 =" + total);
  25.                 try {
  26.                     Thread.sleep(1000);
  27.                 } catch (InterruptedException e) {
  28.                     e.printStackTrace();
  29.                 }
  30.             }
  31.         }
  32.     }
  33. }
复制代码



这里多线程时可以正常运行的  也会显示有两个线程在运行  ,但是我把锁放到run方法上的话,就只有一个线程在运行  为虾米
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-2 04:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表