问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。
代码如下:


package huawei; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * */ public class Demo extends Thread{ private static String tmp ; private static Lock lock = new ReentrantLock(); private static int state =0; static boolean flag; public static String multiThreadWrite(final int times) { tmp =new String(); flag=false; Thread threadA =new Thread() { public void run(){ int count =0; while(count<times) { lock.lock(); if(state%4==0) { tmp += "A"; state++; count++; } lock.unlock(); } } }; Thread threadB =new Thread() { public void run(){ int count =0; while(count<times) { lock.lock(); if(state%4==1) { tmp += "B"; state++; count++; } lock.unlock(); } } }; Thread threadC =new Thread() { public void run(){ int count=0; while(count<times) { lock.lock(); if(state%4==2) { tmp += "C"; state++; count++; } lock.unlock(); } } }; Thread threadD =new Thread() { public void run() { int count =0; while(count<times) { lock.lock(); if(state%4==3) { tmp += "D"; state++; count++; } lock.unlock(); } flag=true; } }; threadA.start(); threadB.start(); threadC.start(); threadD.start(); while(!flag); //防止main线程在四个线程执行完之前就返回tmp值 return tmp; } }
测试代码:


package testcase; import huawei.Demo; import junit.framework.TestCase; public class DemoTest extends TestCase { private void execTestCase(int num) { String rst = Demo.multiThreadWrite(num); String seed = "ABCD"; String chk = new String(); for (int i = 0; i < num; i ++) { chk += seed; } assertEquals(chk, rst); } public void testCase01() { execTestCase(1); } public void testCase03() { execTestCase(15); } }