java线程的实际应用以及线程池

在跑数据时,分为两个线程同时跑:

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();
        }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值