手撕失败

字节二面手撕没撕出来,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();
    }
}

}

全部评论
这个很简单的,有n个线程你就弄n个condition就可以
点赞 回复 分享
发布于 今天 23:19 北京
导util.*不是全导进去了吗
点赞 回复 分享
发布于 今天 16:34 江西

相关推荐

不愿透露姓名的神秘牛友
昨天 10:38
实力求职者:真的绷不住了,第一张霸总人设,第二张求生欲拉满
点赞 评论 收藏
分享
评论
2
4
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务