maoruibin / maoruibin/maoruibin.github.com
主线程等待多个子线程执行完才开始工作的两种实现方式
Open
Nobody has claimed this yet.
article
thread
- Dominant language
- HTML
- Stars
- 22
- Forks
- 4
- PR merge metrics
- No merged PRs in 30d
Description
用 join 实现
public void testJoinOne(){
List<StudentThread>list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
StudentThread thread = new StudentThread(i);
list.add(thread);
thread.start();
}
TeacherThread t = new TeacherThread(list);
t.start();
}
// leader 在等待组员都完成任务
private class TeacherThread extends Thread{
List<StudentThread>list;
public TeacherThread(List<StudentThread> list) {
super();
this.list = list;
}
@Override
public void run() {
super.run();
for(StudentThread thread:list){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
SystemClock.sleep(1000);
Log.d(TAG, "run: 老师干活");
}
}
//工作者在执行任务
private class StudentThread extends Thread{
int i;
public StudentThread(int i) {
super();
this.i = i;
}
@Override
public void run() {
super.run();
SystemClock.sleep(1000);
Log.d(TAG, "学生完成任务 "+i);
}
}
使用 CountDownLatch 实现
final CountDownLatch countDownLatch = new CountDownLatch(8);
private void testCountDown() {
for (int i = 1; i <= 10; i++) {
new WorkerThread(i).start();
}
new LeaderThread().start();
}
// leader 在等待组员都完成任务
private class LeaderThread extends Thread{
@Override
public void run() {
super.run();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "run: 报告老板 Android 组的作业已经全部完成");
}
}
//工作者在执行任务
private class WorkerThread extends Thread{
int i;
public WorkerThread(int i) {
super();
this.i = i;
}
@Override
public void run() {
super.run();
SystemClock.sleep(1000);
countDownLatch.countDown();
Log.d(TAG, "完成任务 "+i +" current latch is "+ countDownLatch.toString());
}
}
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue contains Java and Android thread examples but does not identify a target file, test, or requested change. First determine whether the examples are intended for a blog article and clarify the desired correction or addition; done should be defined against that agreed scope.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- android, java
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100