Google 的一道面试题,老师讲了半天,没做出来,求解
有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:A:1 2 3 4 1 2....
B:2 3 4 1 2 3....
C:3 4 1 2 3 4....
D:4 1 2 3 4 1...
程序代码:package test.copy;
/**
* 有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。
* 现要让四个文件呈如下格式:
*
* A:1 2 3 4 1 2....
*
* B:2 3 4 1 2 3....
*
* C:3 4 1 2 3 4....
*
* D:4 1 2 3 4 1...
*
* @author testadmin
*
*/
public class test implements Runnable {
private int num;
public test(){}
public test(int num) {
this.num = num;
}
public synchronized void run() {
// TODO Auto-generated method stub
System.out.println(num);
}
}
程序代码:package test.copy;
public class testmain {
public void getA(test tt,test tt2,test tt3, test tt4) throws InterruptedException {
System.out.println("A:");
new Thread(tt).start();
new Thread(tt).sleep(10);
new Thread(tt2).start();
new Thread(tt2).sleep(10);
new Thread(tt3).start();
new Thread(tt2).sleep(10);
new Thread(tt4).start();
new Thread(tt4).sleep(10);
}
public void getB(test tt2,test tt3,test tt4, test tt) throws InterruptedException{
System.out.println("B:");
new Thread(tt2).start();
new Thread(tt2).sleep(10);
new Thread(tt3).start();
new Thread(tt3).sleep(10);
new Thread(tt4).start();
new Thread(tt4).sleep(10);
new Thread(tt).start();
new Thread(tt).sleep(10);
}
public void getC(test tt3, test tt4,test tt,test tt2) throws InterruptedException{
System.out.println("B:");
new Thread(tt2).start();
new Thread(tt2).sleep(10);
new Thread(tt3).start();
new Thread(tt3).sleep(10);
new Thread(tt4).start();
new Thread(tt4).sleep(10);
new Thread(tt).start();
new Thread(tt).sleep(10);
}
public void getD(test tt4,test tt,test tt2,test tt3) throws InterruptedException{
System.out.println("B:");
new Thread(tt2).start();
new Thread(tt2).sleep(10);
new Thread(tt3).start();
new Thread(tt3).sleep(10);
new Thread(tt4).start();
new Thread(tt4).sleep(10);
new Thread(tt).start();
new Thread(tt).sleep(10);
}
public static void main(String[] args) throws InterruptedException {
test tt = new test(1);
test tt2 = new test(2);
test tt3 = new test(3);
test tt4 = new test(4);
new Thread(tt).setPriority(10);
new Thread(tt2).setPriority(8);
new Thread(tt3).setPriority(5);
new Thread(tt4).setPriority(1);
testmain ttm = new testmain();
ttm.getA(tt,tt2,tt3,tt4);
System.out.println("******************");
ttm.getB(tt2,tt3,tt4,tt);
System.out.println("******************");
ttm.getC(tt3,tt4,tt,tt2);
System.out.println("******************");
ttm.getD(tt4,tt,tt2,tt3);
}
}
