2个回答
展开全部
package com.main;
仅供楼主参考
public class test {
/**
* @param args
*/
public static void main(String[] args) {
final Bank bank = new Bank();
for(int i = 0; i<10; i++){
new Thread(new Runnable(
){
public void run() {
// TODO Auto-generated method stub
bank.deposit(100);
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
bank.withdraw(100);
}
}).start();
}
}
}
class Bank{
private int total = 1000;
public synchronized void deposit(int num){
total = total +num;
System.out.println("我是存线程"+Thread.currentThread().getName()+"存入了100元");
System.out.println("此时账户余额为:"+total);
}
public synchronized void withdraw(int num){
total = total - num;
System.out.println("我是取线程"+Thread.currentThread().getName()+"存入了100元");
System.out.println("此时账户余额为:"+total);
}
}
仅供楼主参考
public class test {
/**
* @param args
*/
public static void main(String[] args) {
final Bank bank = new Bank();
for(int i = 0; i<10; i++){
new Thread(new Runnable(
){
public void run() {
// TODO Auto-generated method stub
bank.deposit(100);
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
bank.withdraw(100);
}
}).start();
}
}
}
class Bank{
private int total = 1000;
public synchronized void deposit(int num){
total = total +num;
System.out.println("我是存线程"+Thread.currentThread().getName()+"存入了100元");
System.out.println("此时账户余额为:"+total);
}
public synchronized void withdraw(int num){
total = total - num;
System.out.println("我是取线程"+Thread.currentThread().getName()+"存入了100元");
System.out.println("此时账户余额为:"+total);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询