leetcode多线程题目

代码附上了力扣没显示出来的测试

按序打印

class Foo {

    private CountDownLatch latch = new CountDownLatch(1);
    private CountDownLatch sendcondLatch = new CountDownLatch(1);
    public Foo() {

    }

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        latch.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {

        latch.await();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        sendcondLatch.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        sendcondLatch.await();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
    
    public static void main(String[] args) {
        Foo foo = new Foo();
        new Thread(() -> {
            try {
                foo.first(() -> System.out.println("first"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                foo.second(() -> System.out.println("second"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                foo.third(() -> System.out.println("third"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

交替打印FooBar

class FooBar {

    private int n;

    private Semaphore foo = new Semaphore(1);

    private Semaphore bar = new Semaphore(0);

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

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            // 因为有1个许可,所以可以获取到
            foo.acquire();
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            bar.release();

        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            bar.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            foo.release();
        }
    }
    
    public static void main(String[] args) {
        FooBar fooBar = new FooBar(30);
        new Thread(() -> {
            try {
                fooBar.foo(() -> System.out.print("foo"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fooBar.bar(() -> System.out.print("bar"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

打印0与奇偶数

class ZeroEvenOdd {

    private int n;

    private Semaphore zero = new Semaphore(1);
    private Semaphore odd = new Semaphore(1);
    private Semaphore even = new Semaphore(0);


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

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            zero.acquire();
            printNumber.accept(0);
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        int i = 1;
        while (i <= n ) {
            odd.acquire();
            printNumber.accept(i);
            i += 2;
            zero.release();
            even.release();
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        int i = 2;
        while (i <= n) {
            even.acquire();
            printNumber.accept(i);
            i += 2;
            zero.release();
            odd.release();
        }
    }
    
    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(5);
        new Thread(() -> {
            try {
                zeroEvenOdd.zero(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.even(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.odd(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}

H2O

class H2O {

    private final Semaphore hydrogenArrive = new Semaphore(2);
    private final Semaphore oxygenArrive = new Semaphore(1);

    CyclicBarrier barrier = new CyclicBarrier(3);

    public H2O() {

    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {
        try {
            hydrogenArrive.acquire();
            barrier.await();
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();
        }  catch (BrokenBarrierException e) {
            e.printStackTrace();
        } finally {
            hydrogenArrive.release();
        }
    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {
        try {
            oxygenArrive.acquire();
            barrier.await();
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
            releaseOxygen.run();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        } finally {
            oxygenArrive.release();
        }
    }
    
    public static void main(String[] args) {
        H2O h2O = new H2O();
        int n = 10;
        for (int i = 0; i < n*2; i++) {
            new Thread(() -> {
                try {
                    h2O.hydrogen(() -> System.out.print("H"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        for (int i = 0; i < n; i++) {
            new Thread(() -> {
                try {
                    h2O.oxygen(() -> System.out.print("O"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

交替打印字符串

class FizzBuzz {

    private int n;

    private Semaphore normal = new Semaphore(1);

    private Semaphore fizzSm = new Semaphore(0);

    private Semaphore buzzSm = new Semaphore(0);

    private Semaphore fizzBuzzSm = new Semaphore(0);


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

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for (int i = 3; i <= n; i = i + 3) {
//            if (i % 3 == 0 && i % 5 != 0) {
                fizzSm.acquire();
                printFizz.run();
                normal.release();

//            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for (int i = 5; i <= n; i = i + 5) {
//            if (i % 3 != 0 && i % 5 == 0) {

                buzzSm.acquire();
                printBuzz.run();
                normal.release();
//            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for (int i = 15; i <= n; i = i + 15) {
//            if (i % 3 == 0 && i % 5 == 0) {

                fizzBuzzSm.acquire();
                printFizzBuzz.run();
                normal.release();
//            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            normal.acquire();
            if (i % 3 == 0 && i % 5 == 0) {
                fizzBuzzSm.release();
            } else if (i % 3 == 0) {
                fizzSm.release();
            } else if (i % 5 == 0) {
                buzzSm.release();
            } else {
                printNumber.accept(i);
                normal.release();
            }
        }
    }
    
     public static void main(String[] args) throws InterruptedException {
        FizzBuzz fizzBuzz = new FizzBuzz(16);
        new Thread(() -> {
            try {
                fizzBuzz.fizz(() -> System.out.println("fizz"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.buzz(() -> System.out.println("buzz"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.fizzbuzz(() -> System.out.println("fizzBuzz"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                fizzBuzz.number(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

哲学家吃饭问题

下面的方法,只能一个一个的吃,当然也有其他的能一次让两个人吃的解法,不做具体展开。

class DiningPhilosophers2 {

    public DiningPhilosophers2() {

    }

    private Semaphore leftForkPicked = new Semaphore(1);

    private Semaphore rightForkPicked = new Semaphore(1);

    private Semaphore oneByOne = new Semaphore(1);

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
            Runnable pickLeftFork,
            Runnable pickRightFork,
            Runnable eat,
            Runnable putLeftFork,
            Runnable putRightFork) throws InterruptedException {
        oneByOne.acquire();

        pickLeftFork.run();
        pickRightFork.run();
        eat.run();
        putLeftFork.run();
        putRightFork.run();
        leftForkPicked.release();
        rightForkPicked.release();
        oneByOne.release();
    }
    
    public static void main(String[] args) throws InterruptedException {
        DiningPhilosophers philosophers = new DiningPhilosophers();
        Runnable pickLeftFork = () -> System.out.println(Thread.currentThread().getName() + ",1,1]");
        Runnable pickRightFork = () -> System.out.println(Thread.currentThread().getName() + ",2,1]");
        Runnable eat = () -> System.out.println(Thread.currentThread().getName() + ",0,3]");
        Runnable putLeftFork = () -> System.out.println(Thread.currentThread().getName() + ",1,2]");
        Runnable putRightFork = () -> System.out.println(Thread.currentThread().getName() + ",2,2]");
        int num = 5;
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    for (int j = 0; j < num; j++) {

                        philosophers.wantsToEat(finalI, pickLeftFork, pickRightFork, eat, putLeftFork,
                                putRightFork);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "[" + finalI + "").start();
        }
        Thread.currentThread().join();
    }
}
当你准备好了,机会来临的时候,你才能抓住
原文地址:https://www.cnblogs.com/studentytj/p/14860897.html