- 交替打印字符串
- 消除游戏
import java.util.concurrent.locks.*; class FizzBuzz { private int n; public FizzBuzz(int n) { this.n = n; } private ReentrantLock lock = new ReentrantLock(); private Condition fizzCondition = lock.newCondition(); private Condition buzzCondition = lock.newCondition(); private Condition fizzbuzzCondition = lock.newCondition(); private Condition numberCondition = lock.newCondition(); private int i = 1; public void fizz(Runnable printFizz) throws InterruptedException { lock.lock(); try { if (i % 3 != 0) { fizzCondition.await(); } for (; i <= n; ) { printFizz.run(); numberCondition.signal(); fizzCondition.await(); } } finally { lock.unlock(); } } public void buzz(Runnable printBuzz) throws InterruptedException { lock.lock(); try { if (i % 5 != 0) { buzzCondition.await(); } for (; i <= n; ) { printBuzz.run(); numberCondition.signal(); buzzCondition.await(); } } finally { lock.unlock(); } } public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { lock.lock(); try { if (i % 3 != 0 || i % 5 != 0) { fizzbuzzCondition.await(); } for (; i <= n; ) { printFizzBuzz.run(); numberCondition.signal(); fizzbuzzCondition.await(); } } finally { lock.unlock(); } } public void number(SelfIntConsumer printNumber) throws InterruptedException { lock.lock(); try { for (; i <= n; i++) { if (i % 3 != 0 && i % 5 != 0) { printNumber.accept(i); // 打印数字 } else if (i % 3 == 0 && i % 5 != 0) { fizzCondition.signal(); numberCondition.await(); } else if (i % 3 != 0 && i % 5 == 0) { buzzCondition.signal(); numberCondition.await(); } else { fizzbuzzCondition.signal(); numberCondition.await(); } } fizzCondition.signal(); buzzCondition.signal(); fizzbuzzCondition.signal(); } finally { lock.unlock(); } } } class FizzBuzzTest { public static void main(String[] args) { Runnable printFizz = () -> System.out.printf("%s", "fizz "); Runnable printBuzz = () -> System.out.printf("%s", "buzz "); Runnable printFizzBuzz = () -> System.out.printf("%s", "fizzbuzz "); SelfIntConsumer intConsumer = new SelfIntConsumer(); FizzBuzz fb = new FizzBuzz(15); new Thread(() -> { try { fb.fizz(printFizz); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { fb.buzz(printBuzz); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { fb.fizzbuzz(printFizzBuzz); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { fb.number(intConsumer); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } } class SelfIntConsumer { public void accept(int i) { System.out.printf("%d ", i); } }消除游戏
class Solution3 { public int lastRemaining(int n) { int remain = n; int start = 1,step = 1; boolean flag = true; while(remain > 1){ if(flag || remain % 2 != 0){ start += step; } remain /= 2; step *= 2; flag = !flag; } return start; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)