You are given a class with three methods: first(), second(), and third(). These methods are called concurrently by three threads. The goal is to ensure that second() is executed only after first() has been executed, and third() is executed only after second() has been executed. The execution of these methods is asynchronous, and you need to design a mechanism that guarantees the correct order of execution regardless of the operating system’s thread scheduling.
You are given a class FooBar with two methods: foo() and bar(). These methods are called concurrently by two threads. One thread calls foo() while the other calls bar(). You need to modify the program to ensure that the output alternates between ‘foo’ and ‘bar’, and ‘foobar’ is printed exactly n times. The threads should alternate their execution such that foo() is printed first, followed by bar(), and this pattern should continue for n times.
You are given an instance of the class ZeroEvenOdd, which contains three functions: zero, even, and odd. The same instance of ZeroEvenOdd is passed to three different threads. Thread A calls zero() to print zeros, thread B calls even() to print even numbers, and thread C calls odd() to print odd numbers. The goal is to output a sequence of numbers in the order: 0, 1, 2, 3, …, 2n, where n is the given number, and the length of the sequence is 2n. The threads should execute asynchronously, ensuring that the sequence is printed correctly.
You are given a class FizzBuzz that has four methods: fizz(), buzz(), fizzbuzz(), and number(). These methods are executed by four different threads. The goal is to output a sequence of numbers from 1 to n with special rules: if the number is divisible by 3 and 5, print ‘fizzbuzz’; if divisible by 3 but not 5, print ‘fizz’; if divisible by 5 but not 3, print ‘buzz’; otherwise, print the number.
Five philosophers sit at a round table with bowls of spaghetti. Each philosopher alternates between thinking and eating. A philosopher can only eat when both their left and right forks are available. Design a system where no philosopher will starve and they can continue alternating between eating and thinking.