1.问题描述:
某个类有2个方法func1(),func2(),有threadCount个线程,要求所有线程执行完func1(),再执行func2()。
2.分析:
1)所有线程的func1()执行完的标准是什么?
2)线程之间怎样共享变量?
3.代码实现
1)源代码:
/** * */ package com.sunny.www.interview; import java.util.concurrent.atomic.AtomicInteger; /** * 所有线程执行完方法1,再执行方法2 * @author sunny * */ public class Syn2Threads implements Runnable { private AtomicInteger threadCount; public Syn2Threads(AtomicInteger threadCount) { super(); this.threadCount = threadCount; } public AtomicInteger getThreadCount() { return threadCount; } public void setThreadCount(AtomicInteger threadCount) { this.threadCount = threadCount; } private void func1(){ System.out.println(Thread.currentThread().getName() + " execute func1,threadCount=" + threadCount.decrementAndGet()); } private void func2(){ System.out.println(Thread.currentThread().getName() + " execute func2,threadCount=" + threadCount); } @Override public void run() { func1(); synchronized(threadCount){ while (0 < threadCount.get()) { try { System.out.println(Thread.currentThread().getName() + " func1 not finished totally,threadCount=" + threadCount); threadCount.wait(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " wait error"); } } threadCount.notifyAll(); } func2(); } public static void main(String[] args) { int threadCount = 5; Syn2Threads syn2Threads = new Syn2Threads(new AtomicInteger(threadCount)); for(int i = 1; i <= threadCount; i++){ new Thread(syn2Threads,"thread-" + i).start(); } } }
2)运行效果:
thread-2 execute func1,threadCount=4 thread-2 func1 not finished totally,threadCount=3 thread-1 execute func1,threadCount=3 thread-4 execute func1,threadCount=2 thread-4 func1 not finished totally,threadCount=2 thread-1 func1 not finished totally,threadCount=2 thread-5 execute func1,threadCount=1 thread-5 func1 not finished totally,threadCount=1 thread-3 execute func1,threadCount=0 thread-3 execute func2,threadCount=0 thread-5 execute func2,threadCount=0 thread-1 execute func2,threadCount=0 thread-4 execute func2,threadCount=0 thread-2 execute func2,threadCount=0
时间: 2024-12-28 13:47:44