JavaSE-线程同步的实现

    技术2026-02-21  15

    将需要同步的代码块使用放在synchronized(this){}当中,synchronized()当中的参数需要是被共享的对象,只要是被共享的对象当中的内容就行,不局限于this. 例如: 同时对账户余额的一个操作代码实现:

    定义目标账户类

    package synchronizedTest; public class SynchronizedAccount { //账号 private String actno; //余额 private double balance; public SynchronizedAccount(){ } public SynchronizedAccount(String actno, double balance) { this.actno = actno; this.balance = balance; } public void setActno(String actno) { this.actno = actno; } public void setBalance(double balance) { this.balance = balance; } public String getActno() { return actno; } public double getBalance() { return balance; } //取款,必须同步 public void withdraw(double money){ //synchronized的()中填共享的对象 synchronized (this){ double before=this.getBalance(); double after=before-money; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } this.setBalance(after); } } }

    定义取款线程类:

    package synchronizedTest; public class AccountThread extends Thread{ private SynchronizedAccount act; public AccountThread(SynchronizedAccount act) { this.act = act; } public void run(){ double money=5000; act.withdraw(money); System.out.println(Thread.currentThread().getName()+"取款成功,余额:"+act.getBalance()); } }

    定义测试类:

    package synchronizedTest; public class SynchronizedTest { public static void main(String[] args) { SynchronizedAccount act=new SynchronizedAccount("11",10000); AccountThread t1=new AccountThread(act); AccountThread t2=new AccountThread(act); t1.start(); t2.start(); } }
    Processed: 0.026, SQL: 9