java 다중 루틴 문제에서 간단한 입금 실현
2743 단어 ReentrantLock
package com.mnmlist.java.grammar;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Customer {
int total;
public Customer() {
total = 0;
}
public final ReentrantLock lock = new ReentrantLock();// 1:lock final
Random random = new Random();
public void put(int num) {
System.out.println(Thread.currentThread().getName()+":before put "+num+" ,total:" + total);
total += num;
System.out.println(Thread.currentThread().getName()+":after put:" + num + ",total:" + total);
}
public void get(int num) {
System.out.println(Thread.currentThread().getName()+":before get "+num+" ,the total is:" + total);
total -= num;
System.out.println(Thread.currentThread().getName()+":after get " + num + " ,the total is:" + total);
}
}
class PutMoney implements Runnable {
Customer customer;
public PutMoney(Customer customer) {
this.customer = customer;
}
public void run() {
int num = 0;
while (true) {
num = customer.random.nextInt(100);
if (num < 0)
num = -num;
customer.lock.lock();
if (customer.total + num <0) {
customer.lock.unlock();
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
customer.put(num);
customer.lock.unlock();
}
}
}
}
class GetMoney implements Runnable {
Customer customer;
public GetMoney(Customer customer) {
this.customer = customer;
}
public void run() {
int num = 0;
while (true) {
num = customer.random.nextInt(100);
if (num < 0)
num = -num;
customer.lock.lock();
if (customer.total - num < 0) {
customer.lock.unlock();
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
customer.get(num);
customer.lock.unlock();
}
}
}
}
public class BankTheadDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer = new Customer();
PutMoney putMoney = new PutMoney(customer);
GetMoney getMoney = new GetMoney(customer);
Thread t1 = new Thread(putMoney);
Thread t2 = new Thread(getMoney);
t2.start();
t1.start();
}
}
2. 그림도 있고 진실도 있다
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
java 다중 루틴 문제에서 간단한 입금 실현1. 코드에 직접 올리기: 2. 그림도 있고 진실도 있다...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.