阅读本文请先看Java线程类:http://www.omegaxyz.com/2018/04/09/java_threading/
Java提供Executor接口来执行线程池中的任务,提供ExecutorService接口来管理和控制任务。
ExecutorService executor = Executors.newCachedThreadPool();语句将为每个等待的任务创建一个新线程,所有的任务都能并发地执行。
注意要用shutdown()对执行器进行关闭。
假设创建并启动100个线程,每个线程都往一个账户中添加一个便士,以及一个用于创建和启动线程的主类。
当所有线程访问同一个数据源时就会出现数据破坏的问题。因此要用关键字synchronized对deposit()线程进行保护(加锁,互斥信号量)
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.concurrent.*; public class AccountWithoutSync { private static Account account = new Account(); public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); // Create and launch 100 threads for (int i = 0; i < 100; i++) { executor.execute(new AddAPennyTask()); } executor.shutdown(); // Wait until all tasks are finished while (!executor.isTerminated()) { } System.out.println("What is balance? " + account.getBalance()); } // A thread for adding a penny to the account private static class AddAPennyTask implements Runnable { public void run() { account.deposit(1); } } // An inner class for account private static class Account { private int balance = 0; public int getBalance() { return balance; } public synchronized void deposit(int amount) { balance += amount; // This delay is deliberately added to magnify the // data-corruption problem and make it easy to see. try { Thread.sleep(5); } catch (InterruptedException ex) { } balance = newBalance; } } } |
或者对run()这样修改:
1 2 3 4 5 |
public void run() { Synchronized (account){ Account.deposit(1); } } |