log4j和多线程,我在哪里关闭记录器?

时间:2013-06-16 07:56:37

标签: java log4j

我在多线程Web服务中使用log4j。问题是我在哪里关闭记录器? 我试图在程序结束时关闭它,但我有其他线程使用它。

private Logger logger = Logger.getLogger(NewWebServiceFromWSDL.class.getName());
BasicConfigurator.configure();

Thread switchThread = new Thread(new Runnable() {
        @Override
        public void run() {
            logger.info("bla");
            LogManager.shutdown();
        }
    });
    switchThread.start();

1 个答案:

答案 0 :(得分:0)

您可以使用CyclicBarrier。完成所有线程后,可以触发作业关闭Logger。

以下是一个示例代码[取自其他网站并已修改]:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;


public class CyclicBarrierExample {

    //Runnable task for each thread
    private static class Task implements Runnable {

        private CyclicBarrier barrier;

        public Task(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            } catch (BrokenBarrierException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]) {

        //creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await()
        final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //This task will be executed once all thread reaches barrier
                LogManager.shutdown();
            }
        });

        //starting each of thread
        Thread t1 = new Thread(new Task(cb), "Thread 1");
        Thread t2 = new Thread(new Task(cb), "Thread 2");
        Thread t3 = new Thread(new Task(cb), "Thread 3");

        t1.start();
        t2.start();
        t3.start();

    }
}