Skip to content

Instantly share code, notes, and snippets.

@hugozhu
Last active December 16, 2015 07:58
Show Gist options
  • Save hugozhu/5402086 to your computer and use it in GitHub Desktop.
Save hugozhu/5402086 to your computer and use it in GitHub Desktop.
线程等待依赖服务初始化成功 (for android)
package com.github.hugozhu.thread_wait_for_another_s_signal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程等待依赖服务初始化成功 (for android)
* User: hugozhu
* Date: 4/17/13
* Time: 12:14 PM
*/
public class Main {
public static void main(String ... args) throws Exception {
final MyService myService = new MyService();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread 1 trying to wait for service");
myService.awaitForInit();
//put business logic here
System.out.println("thread 1 done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread 2 trying to wait for service");
myService.awaitForInit();
System.out.println("thread 2 done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("thread 3 trying to wait for service");
myService.awaitForInit();
System.out.println("thread 3 done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.setName("Thread1");
thread1.start();
thread2.setName("Thread2");
thread2.start();
Thread.sleep(1000);
myService.init();
Thread.sleep(1000);
thread3.start();
thread3.setName("Thread3");
thread2.join();
thread1.join();
thread3.join();
}
}
class MyService {
CountDownLatch init = new CountDownLatch(1);
public void awaitForInit() throws InterruptedException {
init.await();
}
public void init() {
new Thread(new Runnable() {
@Override
public void run() {
//put your initialization codes here
init.countDown();
System.out.println("init done");
}
}).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment