62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.locks.ReentrantLock;
public class Test{
public static void main(String[] args){
ReentrantLock lock = new ReentrantLock(true);
String[] strs1 = {"1","3","5","7","9"};
String[] strs2 = {"2","4","6","8","10"};
Thread thread1 = getThread(strs1,lock);
Thread thread2 = getThread(strs2,lock);
thread1.start();
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
thread2.start();
}
public static Thread getThread(String[] strs,ReentrantLock lock){
Thread thread = new Thread(){
@Override
public void run(){
for(int i = 0 ; i < strs.length ; i ++){
lock.lock();
System.out.println(strs[i]);
lock.unlock();
try{
Thread.sleep(20);
}catch(Exception e){
e.printStackTrace();
}
}
}
};
return thread;
}
}