在跑数据时,分为两个线程同时跑:
1.创建两个线程
2.两个线程都结束的时候,才继续执行某些东西,通过countDownLatch来计数
private CountDownLatch countDownLatch;
/**
* 跑所有,多线程
*/
public void initGJXF(){
//countDownLatch计数2个
countDownLatch = new CountDownLatch(2);
// 线程1
Runnable myRunnable1 = new Runnable(){
@Override
public void run() {
synchronized(this){
initGJ();
//countDownLatch计数-1
countDownLatch.countDown();
}
}
};
// 线程2
Runnable myRunnable2 = new Runnable(){
@Override
public void run() {
synchronized(this){
baseProjectManager.initXF();
baseTeacherCreditsSumManager.init1();
//baseProjectManager.test2();
//countDownLatch计数-1
countDownLatch.countDown();
}
}
};
Thread thread1 = new Thread(myRunnable1);
thread1.start();
Thread thread2 = new Thread(myRunnable2);
thread2.start();
//方法一:通过阻塞停止,最后执行f
/*
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
//方法二:通过countdownlatch计数执行
try {
//调用await方法阻塞当前线程,等待子线程完成后在继续执行
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据同步完成");
}
3.线程池使用:
try {
// 创建三个线程
ExecutorService threadPool = Executors.newFixedThreadPool(3);
for(int i=1; i<=10; i++){
threadPool.execute(new Runnable(){
public void run() {
// 线程中执行某些事物
try {
System.out.println(Thread.currentThread().getName() + "正在执行xxxx");
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 关闭线程池
threadPool.shutdown();
// 校验线程是否已经全部结束
while (true){
if(threadPool.isTerminated()){
System.out.println("线程池已经结束运行");
break;
}
Thread.sleep(200);
}
System.out.println("继续执行下面的东西");
} catch (InterruptedException e) {
e.printStackTrace();
}