There is this problem called the "1717171717". It sounds really simple but I can't get my head around the algorithm to do it. Here is the problem brief:
Write a concurrent Java program which declares an array of 10 integers. Create two threads. One which writes the value 1 to every element in the array. The second thread writes the value 7 to every element of the array. When both threads have terminated, print out the array. The result when both threads terminate has to be (1,7,1,7,1,7,1,7,...) or (7,1,7,1,7,1,7,...). You will need to use a synchronized method or a synchronized statement to achieve this. Note, each thread must write to every element of the array.
Furthermore, each thread should write to each element only once, I'm told.
Here is what I have. I need an algorithm that will meet this within the run() method. Any help would be appreciated.
import java.util.ArrayList;
class SharedData
{
public static void main(String[] args) throws InterruptedException
{
ArrayList<Integer> data = new ArrayList<>(10);
for (int i = 0; i < 10; i++)
data.add(0);
Writer.array = data;
Thread one = new Thread (new Writer(1), "Ones");
Thread seven = new Thread (new Writer(7), "Sevens");
one.start();
seven.start();
one.join(); seven.join();
data.forEach(System.out::println);
}
}
class Writer implements Runnable
{
public static ArrayList<Integer> array = new ArrayList<>();
final int value;
Writer (int val) {
this.value = val;
}
public void run()
{
for (int i = 0; i < array.size(); i++) {
synchronized (array) {
try
{
//Algorithm?
array.set(i, value);
array.notifyAll();
if (i < array.size()-1)
array.wait();
}
catch (InterruptedException ie) {
System.err.println(ie.getMessage());
}
}
}
System.out.println(Thread.currentThread().getName()+" terminated.");
}
}