有一个余额为3000的账户,现有2个渠道同时存钱,共存6次,打印每次存钱的余额。
package com.yby7; //分析问题 //1:是否为多线程? -->多线程 //2:是否有共享数据? -->线程安全问题 -->同步机制 import java.util.concurrent.locks.ReentrantLock; class Account implements Runnable{ private int balance = 3000; private int cnt = 1; private ReentrantLock lock = new ReentrantLock(); @Override public void run() { while (true) { try { lock.lock(); if (cnt <= 6) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } balance += 1000; cnt ++; System.out.println("当前余额为:"+balance); }else{ break; } }finally { lock.unlock(); } } } } public class AccountTest { public static void main(String[] args) { Account p = new Account(); Thread t1 = new Thread(p); Thread t2 = new Thread(p); t1.setName("窗口1"); t2.setName("窗口2"); t1.start(); t2.start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)