/**
* @Description: 4个线程,其中两个线程每次对J+1,另两个线程每次对J-1
*/
package com;public class ThreadTest{
private int a = 10000;
public ThreadTest(){}
public synchronized boolean save(){
if(a == 0){
System.out.println(Thread.currentThread().getId()+":a已经破产!!");
return false;
}else{
a = a + 100;
System.out.println(Thread.currentThread().getId()+":a存入100元,a余额为"+ a + "元.");
return true;
}
}
public synchronized boolean take(){
if(a == 0){
System.out.println(Thread.currentThread().getId()+":a已经破产!!");
return false;
}else if(a < 1000){
System.out.println(Thread.currentThread().getId()+":b取款失败,辣鸡a余额不足1000元!!");
}else{
a = a - 1000;
System.out.println(Thread.currentThread().getId()+":b取款1000,a余额为"+ a + "元.");
}
return true;
}
public static void main(String args[]) {
System.err.println("初始余额为:10000");
ThreadTest test = new ThreadTest();
AddThread add = test.new AddThread();
MinusThread minus = test.new MinusThread();
new Thread(add, "a").start();
new Thread(minus, "b").start();
new Thread(add, "a").start();
new Thread(minus, "b").start();
}
class AddThread implements Runnable {
@Override
public void run() {
while(save()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MinusThread implements Runnable {
@Override
public void run() {
while(take()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}