手撕失败
字节二面手撕没撕出来,n个线程,打印1~m,线程1打印1,线程2打印2,...线程n打印n,线程1打印n+1 ...
写了个烂代码,但是那个编译器不能自动导包。
手动导包不知道ReentrantLock在哪里,CountDownLatch在哪里
.*只能导入该目录下的类, a.b 和a不是同一个目录
ReentrantLock在java.util.concurrent.locks下,CountDownLatch在java.util.concurrent下
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Main{
public static volatile int s=0;
public static volatile int total=0;
public static void main(String[] args) throws InterruptedException {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();
Thread[] ts=new Thread[n];
ReentrantLock lock=new ReentrantLock(true);
Condition c=lock.newCondition();
CountDownLatch latch=new CountDownLatch(n);
for(int i=0;i<n;i++){
final int id=i;
ts[i]=new Thread(()->{
while(total<m){
lock.lock();
try{
while(true){
if(total==m){
c.signalAll();
latch.countDown();
break;
}else if(s!=id){
c.await();
}else{
total++;
System.out.println(Thread.currentThread().getName()+" "+total);
s=(s+1)%n;
c.signalAll();
}
}
}catch (Exception e){
}finally{
lock.unlock();
}
}
},String.format("线程%d",i+1));
}
for(Thread t:ts)t.start();
latch.await();
}
}
}
查看4道真题和解析