多线程数据的安全性问题

package test0811.thread;

class Account {
	private int balance = 1000;

	public synchronized void qu() {//同步,关键词synchronized,只允许调用者一个一个调用
		if (balance >= 1000) {
			balance -= 1000;
			System.out.println("取了1千元");
		}
	}
}

class MyTT extends Thread {// 创建线程

	private Account account;// 账户属性

	public MyTT() {
	}// 构造方法,new线程对象时,给属性传值

	public MyTT(Account account) {
		this.account = account;

	}

	@Override
	public void run() {// 重写
		try {
			Thread.sleep(100);//睡眠0.1秒
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		account.qu();
	}
}

public class Test04 {

	public static void main(String[] args) {
		// 同步:一件一件事情做,A->B->C... 单线程
		// 异步:同时做多件事情. 多线程

		// 多线程时数据的不安全性问题
		Account account = new Account();// 做账户
		MyTT mt1 = new MyTT(account);
		MyTT mt2 = new MyTT(account);
		MyTT mt3 = new MyTT(account);
		mt1.start();
		mt2.start();
		mt3.start();
	}

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/gcyqweasd/article/details/109905829