- Java 并发教程
- 并发 - 首页
- 并发 - 概览
- 并发 - 环境设置
- 并发 - 主要操作
- 线程间通信
- 并发 - 同步
- 并发 - 死锁
- 实用程序类示例
- 并发 - ThreadLocal
- 并发 - ThreadLocalRandom
- 锁示例
- 并发 - 锁
- 并发 - 读写锁
- 并发 - 条件
- 原子变量示例
- 并发 - AtomicInteger
- 并发 - AtomicLong
- 并发 - AtomicBoolean
- 并发 - AtomicReference
- 并发 - AtomicIntegerArray
- 并发 - AtomicLongArray
- 并发 - AtomicReferenceArray
- 执行程序示例
- 并发 - 执行程序
- 并发 - 执行程序服务
- 安排执行程序服务
- 线程池示例
- 并发 - newFixedThreadPool
- 并发 - newCachedThreadPool
- newScheduledThreadPool
- newSingleThreadExecutor
- 并发 - ThreadPoolExecutor
- ScheduledThreadPoolExecutor
- 高级示例
- 并发 - Future 和 Callable
- 并发 - Fork-Join 框架
- 并发集合
- 并发 - BlockingQueue
- 并发 - ConcurrentMap
- ConcurrentNavigableMap
- 并发有用资源
- 并发 - 快速指南
- 并发 - 有用资源
- 并发 - 讨论
Java 并发 - 同步
带同步的多线程示例
以下是可以按顺序打印计数器值的示例,每次运行结果都相同。
示例
class PrintDemo { public void printCount() { try { for(int i = 5; i > 0; i--) { System.out.println("Counter --- " + i ); } } catch (Exception e) { System.out.println("Thread interrupted."); } } } class ThreadDemo extends Thread { private Thread t; private String threadName; PrintDemo PD; ThreadDemo(String name, PrintDemo pd) { threadName = name; PD = pd; } public void run() { synchronized(PD) { PD.printCount(); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD); ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD); T1.start(); T2.start(); // wait for threads to end try { T1.join(); T2.join(); } catch (Exception e) { System.out.println("Interrupted"); } } }
每次运行此程序时,结果始终相同 −
输出
Starting Thread - 1 Starting Thread - 2 Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 1 exiting. Counter --- 5 Counter --- 4 Counter --- 3 Counter --- 2 Counter --- 1 Thread Thread - 2 exiting.
广告