0

我在我的多线程 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();
4

1 回答 1

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

    }
}
于 2013-06-16T08:01:00.753 回答