日期:2014-05-18 浏览次数:20627 次
import java.util.Arrays;
// 使用三个线程分别对一个长度为3的int数组的每一项加1后由第四个线程输出3个int的值的和。
class AddThread implements Runnable
{
private Lock lock;
private int index;
private int[] arr;
AddThread(Lock lock, int index, int[] arr)
{
this.lock = lock;
this.index = index;
this.arr = arr;
}
@Override
public void run()
{
synchronized (lock)
{
while (lock.allTrue())
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
this.arr[index]++;
System.out.println("index " + index + " 加过了!");
this.lock.setTrue(index);
try
{
Thread.sleep((long) (Math.random() * 300));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
lock.notify();
}
}
}
class PrintThread implements Runnable
{
private Lock lock;
private int[] arr;
PrintThread(Lock lock, int[] arr)
{
this.lock = lock;
this.arr = arr;
}
@Override
public void run()
{
synchronized (lock)
{
while (!lock.allTrue())
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
try
{
Thread.sleep((long) (Math.random() * 300));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int res = 0;
for (int a : arr)
res += a;
System.out.println(Arrays.toString(arr) + "==" + res);
lock.setFalseAll();
lock.notify();
}
}
}
class Lock
{
private boolean[] barr;
Lock(int[] arr)
{
this.barr = new boolean[arr.length];
}
void setTrueAll()
{
Arrays.fill(this.barr, true);
}
void setFalseAll()
{
Arrays.fill(this.barr, false);
}
void setTrue(int i)
{
this.barr[i] = true;
}
void setFalse(int i)
{
this.barr[i] = false;
}
boolean allFalse()
{
for (boolean b : barr)
{
if (b)
return false;
}
return true;
}
boolean allTrue()
{
for (boolean b : barr)
{
if (!b)
return false;
}
return true;
}
}
public class MianShi
{
public static void main(String[] args)
{
int[] arr =
{
1, 2, 3
};
Lock lock = new Lock(arr);
new Thread(new Print