185.
M1(n) = 2M1(n/2) + O(n)
==> M1(n) = O(nlogn)
M∞(n) = M∞(n/2) + O(n)
==> M∞(n) = O(n)
P = M∞(n) / M1(n) = logn
186.
187.
package p187;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ArraySum
{
static ExecutorService Execs = Executors.newCachedThreadPool();
static int Add(int[] data) throws ExecutionException, InterruptedException
{
Result rc = new Result(0);
Future future = Execs.submit(new AddClass(data, 0, data.length - 1, rc));
future.get();
return rc.get();
}
static class Result
{
private int val;
public Result(int val)
{
this.val = val;
}
public int get()
{
return this.val;
}
public void set(int val)
{
this.val = val;
}
}
static class AddClass implements Runnable
{
int[] data;
Result rc;
int lIndex;
int rIndex;
public AddClass(int[] data, int lIndex, int rIndex, Result rc)
{
this.data = data;
this.rc = rc;
this.lIndex = lIndex;
this.rIndex = rIndex;
}
public void run()
{
try
{
if(rIndex < lIndex)
{
rc.set(0);
}else if(lIndex == rIndex)
{
rc.set(data[lIndex]);
}else
{
Result leftRc = new Result(0);
Result rightRc = new Result(0);
int mid = (lIndex + rIndex) / 2;
Future lf = Execs.submit(new AddClass(data, lIndex, mid, leftRc));
Future rf = Execs.submit(new AddClass(data, mid + 1, rIndex, rightRc));
lf.get();
rf.get();
rc.set(leftRc.get() + rightRc.get());
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
188.
T1 <= T4 * 4 = 320; T1 <= T64 * 64 = 320; ==> T1 <= 320;
T∞ <= T4 = 80; T∞ <= T64 = 10; ==> T∞ <= 10;
而且都满足第三个不等式。
T10 <= T1 / 10 + (T∞ * 9) / 10 = 41。
189.
package p189;
public class Matrix
{
private T[][] vcs;
private final int sRow;
private final int eRow;
private final int sCol;
private final int eCol;
private final int rLen;
private final int cLen;
@SuppressWarnings("unchecked")
public Matrix(int rowLen, int colLen)
{
this.vcs = (T[][]) new Object[rowLen][];
for(int i = 0; i < rowLen; i ++)
{
vcs[i] = (T[]) new Object[colLen];
}
sRow = 0;
eRow = rowLen - 1;
sCol = 0;
eCol = colLen - 1;
rLen = rowLen;
cLen = colLen;
}
public Matrix(T[][] vcs, int sRow, int eRow, int sCol, int eCol)
{
this.vcs = vcs;
this.sRow = sRow;
this.eRow = eRow;
this.sCol = sCol;
this.eCol = eCol;
this.rLen = eRow - sRow + 1;
this.cLen = eCol - sCol + 1;
}
public void set(int row, int col, T val) throws Exception
{
if((sRow + row) > eRow) throw new Exception("Invalid row ");
if((sCol + col) > eCol) throw new Exception("Invalid col");
vcs[sRow + row][sCol + col] = val;
}
public T get(int row, int col) throws Exception
{
if((sRow + row) > eRow) throw new Exception("Invalid row ");
if((sCol + col) > eCol) throw new Exception("Invalid col");
return vcs[sRow + row][sCol + col];
}
public int getRowLength()
{
return rLen;
}
public int getColLength()
{
return cLen;
}
@SuppressWarnings("unchecked")
public Matrix[][] split()
{
int mRow = (sRow + eRow) /2;
int mCol = (sCol + eCol) / 2;
Matrix[][] rcs = (Matrix[][]) new Matrix[2][];
for(int i = 0; i < rcs.length; i ++)
{
rcs[i] = (Matrix[]) new Matrix[2];
}
rcs[0][0] = new Matrix(vcs, sRow, mRow, sCol, mCol);
if(sCol == eCol)
{
rcs[0][1] = new Matrix(vcs, 0, -1, 0, -1);
rcs[1][1] = new Matrix(vcs, 0, -1, 0, -1);
}else
{
rcs[0][1] = new Matrix(vcs, sRow, mRow, mCol + 1, eCol);
}
if(sRow == eRow)
{
rcs[1][0] = new Matrix(vcs, 0, -1, 0, -1);
rcs[1][1] = new Matrix(vcs, 0, -1, 0, -1);
}else
{
rcs[1][0] = new Matrix(vcs, mRow + 1, eRow, sCol, mCol);
rcs[1][1] = new Matrix(vcs, mRow + 1, eRow, mCol + 1, eCol);
}
return rcs;
}
public String toString()
{
if(rLen <= 0 || cLen <= 0)
{
return "Empty";
}
StringBuilder str = new StringBuilder();
for(int i = sRow; i <= eRow; i ++)
{
for(int j = sCol; j <= eCol; j ++)
{
str.append(vcs[i][j]);
str.append(", ");
}
str.append("\n");
}
return str.toString();
}
public static void main(String[] args)
{
Integer[][] data = new Integer[8][];
for(int i = 0; i < data.length; i ++)
{
data[i] = new Integer[8];
}
for(int i = 0; i < data.length; i ++)
{
for(int j = 0; j < data[i].length; j ++)
{
data[i][j] = i * 10 + j;
}
}
Matrix m = new Matrix(data, 0, data.length - 1, 0, data[0].length - 1);
while(m.getRowLength() > 0)
{
System.out.println(m);
Matrix[][] subMs = m.split();
for(int i = 0; i < subMs.length; i ++)
{
for(int j = 0; j < subMs[i].length; j ++)
{
System.out.println(subMs[i][j]);
}
}
m = subMs[1][1];
}
}
}
190.
package p190;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PolyOp
{
static ExecutorService Execs = Executors.newCachedThreadPool();
static Long Op(int x, Polynomial leftPrefix, Polynomial rightPrefix, OP op) throws ExecutionException, InterruptedException
{
long xs[] = new long[leftPrefix.getDegree() * 2];
long sum = 1;
for(int i = 0; i < xs.length; i ++)
{
xs[i] = sum;
sum *= x;
}
Result rc = new Result((long)0);
Future f = Execs.submit(new OpClass(leftPrefix, rightPrefix, xs, rc, op));
f.get();
return rc.get();
}
static class Result
{
private T val;
public Result(T val)
{
this.val = val;
}
public T get()
{
return this.val;
}
public void set(T val)
{
this.val = val;
}
}
static enum OP
{
ADD,
MUL,
};
static class OpClass implements Runnable
{
private Polynomial leftPrefix;
private Polynomial rightPrefix;
private final long x[];
private Result rc;
private final OP op;
public OpClass(Polynomial leftPrefix, Polynomial rightPrefix, long x[], Result rc, OP op)
{
this.leftPrefix = leftPrefix;
this.rightPrefix = rightPrefix;
this.x = x;
this.rc = rc;
this.op = op;
}
private void add()
{
try
{
if(leftPrefix.getDegree() == 1)
{
rc.set(new Long(leftPrefix.get(0) + rightPrefix.get(0)));
}else
{
Result fRc = new Result((long)0);
Result lRc = new Result((long)0);
Polynomial[] leftPs = leftPrefix.split();
Polynomial[] rightPs = rightPrefix.split();
Future ff = Execs.submit(new OpClass(leftPs[0], rightPs[0], x, fRc, op));
Future lf = Execs.submit(new OpClass(leftPs[1], rightPs[1], x, lRc, op));
ff.get();
lf.get();
long result = fRc.get() + lRc.get() * x[leftPs[0].getDegree()];
rc.set(result);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
private void mul()
{
try
{
if(leftPrefix.getDegree() == 1)
{
rc.set(new Long(leftPrefix.get(0) * rightPrefix.get(0)));
}else
{
Result fRc = new Result((long)0);
Result lRc = new Result((long)0);
Result mRc1 = new Result((long)0);
Result mRc2 = new Result((long)0);
Polynomial[] leftPs = leftPrefix.split();
Polynomial[] rightPs = rightPrefix.split();
Future ff = Execs.submit(new OpClass(leftPs[0], rightPs[0], x, fRc, op));
Future fm1 = Execs.submit(new OpClass(leftPs[0], rightPs[1], x, mRc1, op));
Future fm2 = Execs.submit(new OpClass(leftPs[1], rightPs[0], x, mRc2, op));
Future fr = Execs.submit(new OpClass(leftPs[1], rightPs[1], x, lRc, op));
ff.get();
fr.get();
fm1.get();
fm2.get();
long result = fRc.get() + (lRc.get() * x[leftPrefix.getDegree()]) + (mRc1.get() + mRc2.get()) * x[leftPs[0].getDegree()];
rc.set(result);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
switch(op)
{
case ADD:
add();
break;
case MUL:
mul();
break;
default:
System.out.println("Invalid op");
break;
}
}
}
public static void main(String[] args)
{
int degree = 4;
Polynomial left = new Polynomial(degree);
Polynomial right = new Polynomial(degree);
for(int i = 0; i < left.getDegree(); i ++)
{
left.set(i, 1);
right.set(i, 1);
}
try
{
long rc = PolyOp.Op(2, left, right, PolyOp.OP.MUL);
System.out.println("Get " + rc);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
191.
矩阵2分,8个线程做乘法。然后n^2个线程做加法。
==> M∞(n) = M∞(n/2) + O(1) ==> M∞(n) = O(logn)
==> M1(n) = 8 * M(n/2) + O(n^2) ==> M1(n) = O(n^3)
package p191;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import p189.Matrix;
public class MatrixMul
{
static ExecutorService Execs = Executors.newCachedThreadPool();
public static void MUL(Matrix a, Matrix b, Matrix c) throws ExecutionException, InterruptedException
{
Future f = Execs.submit(new MultiClass(a, b, c));
f.get();
return;
}
static class MultiClass implements Runnable
{
private Matrix a;
private Matrix b;
private Matrix c;
public MultiClass(Matrix a, Matrix b, Matrix c)
{
this.a = a;
this.b = b;
this.c = c;
}
public void run()
{
if(a.getRowLength() == 0 || a.getColLength() == 0)
{
return;
}
if(a.getRowLength() == 1 && a.getColLength() == 1)
{
try
{
c.set(0, 0, a.get(0, 0) * b.get(0, 0));
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
if(a.getColLength() > 1 || a.getRowLength() > 1)
{
try
{
Matrix as[][] = a.split();
Matrix bs[][] = b.split();
Future[] fs = new Future[8];
Matrix tcs0 = new Matrix(as[0][0].getRowLength(), bs[0][0].getColLength());
Matrix tcs1 = new Matrix(as[0][0].getRowLength(), bs[0][1].getColLength());
Matrix tcs2 = new Matrix(as[1][0].getRowLength(), bs[0][0].getColLength());
Matrix tcs3 = new Matrix(as[1][0].getRowLength(), bs[0][1].getColLength());
Matrix tcs4 = new Matrix(as[0][1].getRowLength(), bs[1][0].getColLength());
Matrix tcs5 = new Matrix(as[0][1].getRowLength(), bs[1][1].getColLength());
Matrix tcs6 = new Matrix(as[1][1].getRowLength(), bs[1][0].getColLength());
Matrix tcs7 = new Matrix(as[1][1].getRowLength(), bs[1][1].getColLength());
fs[0] = Execs.submit(new MultiClass(as[0][0], bs[0][0], tcs0));
fs[1] = Execs.submit(new MultiClass(as[0][0], bs[0][1], tcs1));
fs[2] = Execs.submit(new MultiClass(as[1][0], bs[0][0], tcs2));
fs[3] = Execs.submit(new MultiClass(as[1][0], bs[0][1], tcs3));
fs[4] = Execs.submit(new MultiClass(as[0][1], bs[1][0], tcs4));
fs[5] = Execs.submit(new MultiClass(as[0][1], bs[1][1], tcs5));
fs[6] = Execs.submit(new MultiClass(as[1][1], bs[1][0], tcs6));
fs[7] = Execs.submit(new MultiClass(as[1][1], bs[1][1], tcs7));
for(int i = 0; i < fs.length; i ++)
{
fs[i].get();
}
Future[][] rcFs = new Future[c.getRowLength()][];
for(int i = 0; i < rcFs.length; i ++)
{
rcFs[i] = new Future[c.getColLength()];
}
for(int i = 0; i < tcs0.getRowLength(); i ++)
{
for(int j = 0; j < tcs0.getColLength(); j ++)
{
rcFs[i][j] = Execs.submit(new MatrixAddClass(tcs0, tcs4, c, i, j, i, j));
}
}
for(int i = 0; i < tcs1.getRowLength(); i ++)
{
for(int j = 0; j < tcs1.getColLength(); j ++)
{
rcFs[i][j + tcs0.getColLength()] = Execs.submit(new MatrixAddClass(tcs1, tcs5, c, i, j, i, j + tcs0.getColLength()));
}
}
for(int i = 0; i < tcs2.getRowLength(); i ++)
{
for(int j = 0; j < tcs2.getColLength(); j ++)
{
rcFs[i + tcs0.getRowLength()][j] = Execs.submit(new MatrixAddClass(tcs2, tcs6, c, i, j, i + tcs0.getRowLength(), j));
}
}
for(int i = 0; i < tcs3.getRowLength(); i ++)
{
for(int j = 0; j < tcs3.getColLength(); j ++)
{
rcFs[i + tcs0.getRowLength()][j + tcs0.getColLength()] =
Execs.submit(new MatrixAddClass(tcs3, tcs7, c, i, j, i + tcs0.getRowLength(), j + tcs0.getColLength()));
}
}
for(int i = 0; i < rcFs.length; i ++)
{
for(int j = 0; j < rcFs[i].length; j ++)
{
rcFs[i][j].get();
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
static class MatrixAddClass implements Runnable
{
private Matrix a;
private Matrix b;
private Matrix c;
private int srcRow;
private int dstRow;
private int srcCol;
private int dstCol;
public MatrixAddClass(Matrix a, Matrix b, Matrix c, int srcRow, int srcCol, int dstRow, int dstCol)
{
this.a = a;
this.b = b;
this.c = c;
this.srcRow = srcRow;
this.dstRow = dstRow;
this.srcCol = srcCol;
this.dstCol = dstCol;
}
public void run()
{
Integer val = 0;
try
{
val = a.get(srcRow, srcCol) + b.get(srcRow, srcCol);
}catch(Exception e)
{
e.printStackTrace();
val = 0;
}
try
{
c.set(dstRow, dstCol, val);
}catch(Exception ie)
{
ie.printStackTrace();
}
}
}
}
192.
因为size是不断变化的。有可能T1上锁时qa.size() < qb.size(); T2上锁时qa.size() > qb.size()。以交叉的顺序取锁可能造成死锁。
193.
1. 如果不是volatile, 因为popTop是用top和bottom的index判断队列空,所以将会有错误的判断。比如说
T1.popBottom() --> T1.(bottom = 0) --> T1.CAS(top) ==> top = 0 && pop task[0];
T2.popTop() --> T2读到没有同步的bottom = 1 && oldTop = 0 ==> bottom > oldTop ==> T2.CAS(top) --> T2.pop task[0]
将破坏mutual
2. 可以尽早使popTop()得到bottom <= oldTop。 图中23行应该是最早的安全位置。因为bottom由popBottom控制,最早使bottom = 0也要在取得相关值并且满足条件之后,即最早在23行。在此之后,popTop和popBottom都统一的由CAS(top)取到可线性化性。之后不论是谁在此尝试都得知bottom = 0,即队列为空。如果没有现成操作pop,push将会使队列溢出。
194.
1. 因为如果先CAS然后取值,在这2个操作中间,task[oldTop]可能会被popBottom()和pushBottom()覆盖。
2.可以。因为isEmpty将获取最新的值,如果isEmpty() == TRUE,那么确实队列为空。如果isEmpty() == FALSE,则在这段时间中,top和bottom的值可能有变化。但是没有关系,可以看成在不用isEmpty()的算法中取值和CAS中间的时间的变化。
195.
pushBottom():
bottom = oldBottom + 1。 如果bottom没有被改变,pop都不能看到这个task。
popTop():
if(size <= 0) return null 或者 top.CAS
popBottom():
line20 or line 22 or line 27
196.
public Runnable popTop()
{
while(true)
{
int[] stamp = new int[1];
int oldTop = top.get(stamp);
int newTop = oldTop + 1;
int oldStamp = stamp[0];
int newStamp = oldStamp + 1;
if(bottom <= oldTop)
{
return null;
}
Runnable r = task[oldTop];
if(top.compareAndSet(oldTop, newTop, oldStamp, newStamp))
{
return r;
}
}
//impossible
return null;
}
197.
不能。因为pop方法内部都有同样功能的判断,而且读到的是比isEmpty读到的更新的值,并且2这实现上的开销基本相同。如果isEmpty与pop当中的非空判断得到同样的结果,则用户代码中没有调用这个方法也没有关系;如果结果不相同,则调用isEmpty是浪费时间