今天面试有一编程题,多线程相关:
使用三个线程分别对一个长度为3的int数组的每一项加1后由第四个线程输出3个int的值的和。
对多线程不怎么熟悉,恳请大牛们啊~~~
------解决方案--------------------
先上一个最烂的:木有经过深思熟虑,随手写的。
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 PrintThread(lock, arr)).start();
new Thread(new AddThread(lock, 0, arr)).start();
new Thread(new AddThread(lock, 1, arr)).start();
new Thread(new AddThread(lock, 2, arr)).start();
}
}
------解决方案--------------------
三个线程,挨个访问这个数组
当然得先锁死,然后释放,这样才能一个个访问
------解决方案--------------------
三个线程嘛,估计是这意思
1个线程做取内容,扔进队列
1个线程做加法
1个线程取队列求和