【发布时间】:2016-02-02 16:07:02
【问题描述】:
这个问题叫做“1717171717”。这听起来很简单,但我无法理解算法来做到这一点。这是问题简介:
编写一个并发 Java 程序,它声明一个由 10 个整数组成的数组。创建两个线程。将值 1 写入数组中的每个元素的一种。第二个线程将值 7 写入数组的每个元素。当两个线程都终止时,打印出数组。 两个线程终止时的结果必须是 (1,7,1,7,1,7,1,7,...) 或 (7,1,7,1,7,1,7,...) .您将需要使用同步方法或同步语句来实现此目的。注意,每个线程都必须写入数组的每个元素。
此外,有人告诉我,每个线程只能对每个元素写入一次。
这就是我所拥有的。我需要一个在 run() 方法中满足这一点的算法。任何帮助将不胜感激。
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.");
}
}
【问题讨论】:
-
我能问一下为什么我的问题得到了这么多反对吗?
-
你应该使用数组,而不是数组列表。
标签: java multithreading concurrency synchronization