其他分享
首页 > 其他分享> > 多线程的几种使用方法

多线程的几种使用方法

作者:互联网

题目

lc1115交替打印FooBar

Java

BLOCKING Queue

BLOCKING QUEUE的性质:

  1. take()为空时会阻塞
  2. put()超出size时会阻塞
//17ms 41.4MB
class FooBar {
    private int n;  
    private BlockingQueue<Integer> foo = new LinkedBlockingQueue<>(1);
    private BlockingQueue<Integer> bar = new LinkedBlockingQueue<>(1);
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            foo.put(1);
        	printFoo.run();
            bar.put(1);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            bar.take();
        	printBar.run();
            foo.take();
        }
    }   
}

volatile + yield

//18ms 40.9 MB
class FooBar {
    private int n;
    volatile int cur;

    public FooBar(int n) {
        this.n = n;
        cur = 0;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            while(cur == 1) Thread.yield();
        	// printFoo.run() outputs "foo". Do not change or remove this line.
        	printFoo.run();
            cur ^= 1;
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        for (int i = 0; i < n; i++) {
            while(cur == 0) Thread.yield();
            // printBar.run() outputs "bar". Do not change or remove this line.
        	printBar.run();
            cur ^= 1;
        }
    }   
}

CyclicBarrier阻塞

CyclicBarrier阻塞直到所有线程都到达才运行

效率太低,没咋看

//21ms 41.7MB
class FooBar {
    private int n;

    public FooBar(int n) {
        this.n = n;
    }

    CyclicBarrier cb = new CyclicBarrier(2);
    volatile boolean fin = true;

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while(!fin);
            printFoo.run();
            fin = false;
            try {
               cb.await();
            } catch (BrokenBarrierException e) {}
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            try {
                cb.await();
            } catch (BrokenBarrierException e) {}
            printBar.run();
            fin = true;
        }
    }
}

标签:printBar,run,int,FooBar,几种,printFoo,多线程,方法,public
来源: https://www.cnblogs.com/attack204/p/16210432.html