|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- public class Homework02 {
- public static void main(String[] args) {
- User user = new User();
- Thread thread1 = new Thread(user);
- thread1.setName("t1");
- Thread thread2= new Thread(user);
- thread2.setName("t2");
- thread1.start();
- thread2.start();
- }
- }
- class User implements Runnable {
- private boolean loop = true;
- private int total = 10000;
- @Override
- public void run() {
- while (loop) {
- synchronized (this) {
- if (total < 1000) {
- System.out.println("余额不足1000");
- break;
- }
- total -= 1000;
- System.out.println(Thread.currentThread().getName() + "取走一千块钱" + " 余额 =" + total);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码
这里多线程时可以正常运行的 也会显示有两个线程在运行 ,但是我把锁放到run方法上的话,就只有一个线程在运行 为虾米 |
|