JAVA Thread Example

2014-11-24 09:49:23 · 作者: · 浏览: 0

Thread Example

public class Account {

private String accountNo;

private double balance;

public Account(){}

public Account(String accountNo,double balance){

this.accountNo = accountNo;

this.balance = balance;

}

public double getBalance(){

return this.balance;

}

public void draw(double drawAmount){

if(balance >= drawAmount){

System.out.println(Thread.currentThread().getName()+ " " +drawAmount);

balance -= drawAmount;

System.out.println("leftmoney is "+balance);

}else{

System.out.println(Thread.currentThread().getName()+ " failed");

}

}

public inthashCode(){

return accountNo.hashCode();

}

public boolean equals(Object obj){

if(obj==this){

return true;

}

if(obj!=null&obj.getClass()==Account.class){

Accounttarget = (Account)obj;

return target.accountNo.equals(accountNo);

}

return false;

}

}

class DrawThread1 extends Thread{

private Account account;

private double drawAmount;

public DrawThread1(String name,Account account,double drawAmount){

super(name);

this.account = account;

this.drawAmount = drawAmount;

}

public void run(){

account.draw(drawAmount);

}

}

public class DrawThread{

public static void main(String[] args){

Account acct = new Account("1234567",1000);

new DrawThread1("1",acct,800).start();

new DrawThread1("2",acct,800).start();

}

}

Output:

1800.0

leftmoney is 200.0

2800.0

left money is -600.0

public class DrawThread{

public static void main(String[] args) throws InterruptedException{

Account acct = new Account("1234567",1000);

new DrawThread1("1",acct,800).start();

Thread.sleep(100);

new DrawThread1("2",acct,800).start();

}

}

Output:

1800.0

leftmoney is 200.0

2 failed

为了让Account能更好地使用多线程环境,可以将Account类修改为线程安全的方式,线程安全的类具有如下特征:

该类的对象可以被多个线程安全地访问;

每个线程调用该对象的任意方法之后都将得到正确结果;

每个线程调用该对象的任意方法之后,该对象状态依然保持合理状态。

public synchronized double getBalance(){

return this.balance;

}

public synchronized void draw(double drawAmount){

if(balance >= drawAmount){

System.out.println(Thread.currentThread().getName()+ " " +drawAmount);

balance -= drawAmount;

System.out.println("leftmoney is "+balance);

}else{

System.out.println(Thread.currentThread().getName()+ " failed");

}