import java.io.*;
public class Deposit{
static int balance = 1000;
public static void main(String[] ages){
PrintWriter out = new PrintWriter(System.out,true);
Account account=new Account(out);
DepositThread first,second;
first=new DepositThread(account,1000, "#1 ");
second=new DepositThread(account,1000, "\t\t\t\t#2 ");
first.start();
second.start();
try{
first.join();
second.join();
}
catch(InterruptedException e){}
out.println( "***Final balance is "+balance);
}
}
class Account{
PrintWriter out;
Account(PrintWriter out){
this.out=out;
}
void deposit(int amount,String name){
int balance;
out.println(name+ "trying to deposit "+amount);
out.println(name+ "getting balance... ");
balance = getBalance();
out.println(name+ "balance got is "+balance);
balance+=amount;
out.println(name+ "setting balance... ");
setBalance(balance);
out.println(name+ "new balanace set to "+Deposit.balance);
}
int getBalance(){
try{
Thread.sleep(5000);
}
catch(InterruptedException e){}
return Deposit.balance;
}
void setBalance(int balance){
try{
Thread.sleep(5000);
}
catch(InterruptedException e){}
Deposit.balance=balance;
}
}
class DepositThread extends Thread{
Account account;
int depositAmount;
String message;
DepositThread(Account account,int amount,String message){
this.message = message;
this.account=account;
this.depositAmount=amount;
}
public void run(){
account.deposit(depositAmount,message);
}
}
在上面的程序中..为什么要用PrintWriter out=new PrintWriter(System.out,true)这样一句呐?它的作用是什么啊?
谢谢..
------解决方案--------------------
就是对 System.out 封装一下
不过在你的程序中应该是多此一举
因为只是简单的输出一个数字
------解决方案--------------------
PrintWriter
public PrintWriter(OutputStream out)根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter。此便捷构造方法创建必要的中间 OutputStreamWriter,后者使用默认字符编码将字符转换为字节。
参数:
out - 输出流
另请参见:
OutputStreamWriter.OutputStreamWriter(java.io.OutputStream)
--------------------------------------------
自己查一下JavaDoc就知道了
http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/index.html