package huawei;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/***/
public classDemo extends Thread{private staticString tmp ;private static Lock lock = newReentrantLock();private static int state =0;staticboolean flag;public static String multiThreadWrite(final inttimes) {
tmp=newString();
flag=false;
Thread threadA=newThread()
{public voidrun(){int count =0;while(count
{lock.lock();if(state%4==0)
{
tmp+= "A";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadB=newThread()
{public voidrun(){int count =0;while(count
{lock.lock();if(state%4==1)
{
tmp+= "B";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadC=newThread()
{public voidrun(){int count=0;while(count
{lock.lock();if(state%4==2)
{
tmp+= "C";
state++;
count++;
}lock.unlock();
}
}
};
Thread threadD=newThread()
{public voidrun()
{int count =0;while(count
{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值
returntmp;
}
}