java多线程问题,我是新手,不会做啦。 各位大神帮帮忙啊
1个回答
展开全部
package cn.feng;
public class TMoney {
private static int money = 0;
private static Object lock = new Object();
private static int flag = 1;
public static void main(String[] args) throws InterruptedException {
Thread ft = new Thread() {
public void run() {
// compute primes larger than minPrime
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lock) {
if (flag == 1) {
flag = 2;
money = money + 100;
System.out.println("父亲挣100元");
System.out.println("余额为" + money);
} else {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
Thread mt = new Thread() {
public void run() {
// compute primes larger than minPrime
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lock) {
if (flag == 2) {
flag = 3;
if ((money - 80) >= 0) {
money = money - 80;
System.out.println("母亲花钱80");
} else {
System.out.println("母亲钱不够花");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("余额为" + money);
} else {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
Thread st = new Thread() {
public void run() {
// compute primes larger than minPrime
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lock) {
if (flag == 3) {
flag = 1;
if ((money - 30) >= 0) {
money = money - 30;
System.out.println("儿子花钱30");
} else {
System.out.println("儿子钱不够花");
}
System.out.println("余额为" + money);
} else {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
ft.start();
mt.start();
st.start();
}
}
才编的望采纳。有什么不明白的额可以在问
追问
有点乱。 能不能用两个类来给我分一下呀,分不是问题。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询