關於執行緒同步的問題(方法同步和程式碼塊同步)
阿新 • • 發佈:2019-01-11
package com.bootdo.wang; /** * 執行緒同步: * 1.方法同步 * 2.程式碼塊同步 */ public class ThreadSynchronization { class Bank { private int account = 10; public int getAccount() { return account; } /** * 同步方法 * * @param money */ public synchronized void saveAccount(int money) { account += money; } /** * 同步程式碼塊 * * @param money */ public void saveAccount1(int money) { synchronized (this) { account += money; } } } class NewThred implements Runnable { private Bank bank; public NewThred(Bank bank) { this.bank = bank; } @Override public void run() { for (int i = 0; i < 10; i++) { bank.saveAccount1(1); // bank.seveAccount(1); System.out.println(Thread.currentThread().getName() + "-->第" + i + "次,賬戶餘額:" + bank.getAccount()); } } } public void useThread() { Bank bank = new Bank(); NewThred newThred = new NewThred(bank); System.out.println("執行緒1:"); Thread thread1 = new Thread(newThred); thread1.start(); System.out.println("執行緒2:"); Thread thread2 = new Thread(newThred); thread2.start(); } public static void main(String[] args) { ThreadSynchronization threadSynchronization = new ThreadSynchronization(); threadSynchronization.useThread(); } }
輸出:
執行緒1: 執行緒2: Thread-0-->第0次,賬戶餘額:11 Thread-1-->第0次,賬戶餘額:13 Thread-0-->第1次,賬戶餘額:13 Thread-1-->第1次,賬戶餘額:14 Thread-0-->第2次,賬戶餘額:15 Thread-1-->第2次,賬戶餘額:16 Thread-0-->第3次,賬戶餘額:17 Thread-1-->第3次,賬戶餘額:18 Thread-0-->第4次,賬戶餘額:19 Thread-1-->第4次,賬戶餘額:20 Thread-0-->第5次,賬戶餘額:21 Thread-1-->第5次,賬戶餘額:22 Thread-0-->第6次,賬戶餘額:23 Thread-1-->第6次,賬戶餘額:24 Thread-0-->第7次,賬戶餘額:25 Thread-1-->第7次,賬戶餘額:26 Thread-0-->第8次,賬戶餘額:27 Thread-1-->第8次,賬戶餘額:28 Thread-0-->第9次,賬戶餘額:29 Thread-1-->第9次,賬戶餘額:30