barriers / 阅读 / 详情

JAVA里有没有类似SLEEP的函数

2023-07-25 12:22:59
共1条回复
cloudcone

countdownlatch

相关推荐

countdownlatch的await超时时间设置多少合适

CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则处于等待状态,调用countDown()方法就将计数器减1,当计数到达0时,则所有等待者或单个等待者开始执行。
2023-07-24 20:05:581

Java编写程序,分别使用顺序流和并行流计算10,、20、30和40这几个数的阶乘,输出结果及完成计算的时间。

我、提、供、编、码。
2023-07-24 20:06:183

Java线程安全和非线程安全

  ArrayList和Vector有什么区别?HashMap和HashTable有什么区别?StringBuilder和StringBuffer有什么区别?这些都是Java面试中常见的基础问题 面对这样的问题 回答是 ArrayList是非线程安全的 Vector是线程安全的 HashMap是非线程安全的 HashTable是线程安全的 StringBuilder是非线程安全的 StringBuffer是线程安全的 因为这是昨晚刚背的《Java面试题大全》上面写的 此时如果继续问 什么是线程安全?线程安全和非线程安全有什么区别?分别在什么情况下使用?这样一连串的问题 一口老血就喷出来了…   非线程安全的现象模拟   这里就使用ArrayList和Vector二者来说明   下面的代码 在主线程中new了一个非线程安全的ArrayList 然后开 个线程分别向这个ArrayList里面添加元素 每个线程添加 个元素 等所有线程执行完成后 这个ArrayList的size应该是多少?应该是 个?   [java]   public class Main   {   public static void main(String[] args)   {   // 进行 次测试   for(int i = ; i < ; i++)   {   test();   }   }   public static void test()   {   // 用来测试的List   List<Object> list = new ArrayList<Object>();   // 线程数量( )   int threadCount = ;   // 用来让主线程等待threadCount个子线程执行完毕   CountDownLatch countDownLatch = new CountDownLatch(threadCount);   // 启动threadCount个子线程   for(int i = ; i < threadCount; i++)   {   Thread thread = new Thread(new MyThread(list countDownLatch));   thread start();   }   try   {   // 主线程等待所有子线程执行完成 再向下执行   countDownLatch await();   }   catch (InterruptedException e)   {   e printStackTrace();   }   // List的size   System out println(list size());   }   }   class MyThread implements Runnable   {   private List<Object> list;   private CountDownLatch countDownLatch;   public MyThread(List<Object> list CountDownLatch countDownLatch)   {   this list = list;   untDownLatch = countDownLatch;   }   public void run()   {   // 每个线程向List中添加 个元素   for(int i = ; i < ; i++)   {   list add(new Object());   }   // 完成一个子线程   untDown();   }   }   public class Main   {   public static void main(String[] args)   {   // 进行 次测试   for(int i = ; i < ; i++)   {   test();   }   }   public static void test()   {   // 用来测试的List   List<Object> list = new ArrayList<Object>();   // 线程数量( )   int threadCount = ;   // 用来让主线程等待threadCount个子线程执行完毕   CountDownLatch countDownLatch = new CountDownLatch(threadCount);   // 启动threadCount个子线程   for(int i = ; i < threadCount; i++)   {   Thread thread = new Thread(new MyThread(list countDownLatch));   thread start();   }   try   {   // 主线程等待所有子线程执行完成 再向下执行   countDownLatch await();   }   catch (InterruptedException e)   {   e printStackTrace();   }   // List的size   System out println(list size());   }   }   class MyThread implements Runnable   {   private List<Object> list;   private CountDownLatch countDownLatch;   public MyThread(List<Object> list CountDownLatch countDownLatch)   {   this list = list;   untDownLatch = countDownLatch;   }   public void run()   {   // 每个线程向List中添加 个元素   for(int i = ; i < ; i++)   {   list add(new Object());   }   // 完成一个子线程   untDown();   }   }   上面进行了 次测试(为什么要测试 次?因为非线程安全并不是每次都会导致问题)   输出结果                                 上面的输出结果发现 并不是每次测试结果都是 有好几次测试最后ArrayList的size小于 甚至时不时会抛出个IndexOutOfBoundsException异常 (如果没有这个现象可以多试几次)   这就是非线程安全带来的问题了 上面的代码如果用于生产环境 就会有隐患就会有BUG了   再用线程安全的Vector来进行测试 上面代码改变一处 test()方法中   [java]   List<Object> list = new ArrayList<Object>();   List<Object> list = new ArrayList<Object>();改成   [java]   List<Object> list = new Vector<Object>();   List<Object> list = new Vector<Object>();   再运行程序   输出结果                                 再多跑几次 发现都是 没有任何问题 因为Vector是线程安全的 在多线程操作同一个Vector对象时 不会有任何问题   再换成LinkedList试试 同样还会出现ArrayList类似的问题 因为LinkedList也是非线程安全的   二者如何取舍   非线程安全是指多线程操作同一个对象可能会出现问题 而线程安全则是多线程操作同一个对象不会有问题   线程安全必须要使用很多synchronized关键字来同步控制 所以必然会导致性能的降低   所以在使用的时候 如果是多个线程操作同一个对象 那么使用线程安全的Vector 否则 就使用效率更高的ArrayList   非线程安全!=不安全   有人在使用过程中有一个不正确的观点 我的程序是多线程的 不能使用ArrayList要使用Vector 这样才安全   非线程安全并不是多线程环境下就不能使用 注意我上面有说到 多线程操作同一个对象 注意是同一个对象 比如最上面那个模拟 就是在主线程中new的一个ArrayList然后多个线程操作同一个ArrayList对象   如果是每个线程中new一个ArrayList 而这个ArrayList只在这一个线程中使用 那么肯定是没问题的   线程安全的实现   线程安全是通过线程同步控制来实现的 也就是synchronized关键字   在这里 我用代码分别实现了一个非线程安全的计数器和线程安全的计数器Counter 并对他们分别进行了多线程测试   非线程安全的计数器   [java]   public class Main   {   public static void main(String[] args)   {   // 进行 次测试   for(int i = ; i < ; i++)   {   test();   }   }   public static void test()   {   // 计数器   Counter counter = new Counter();   // 线程数量( )   int threadCount = ;   // 用来让主线程等待threadCount个子线程执行完毕   CountDownLatch countDownLatch = new CountDownLatch(threadCount);   // 启动threadCount个子线程   for(int i = ; i < threadCount; i++)   {   Thread thread = new Thread(new MyThread(counter countDownLatch));   thread start();   }   try   {   // 主线程等待所有子线程执行完成 再向下执行   countDownLatch await();   }   catch (InterruptedException e)   {   e printStackTrace();   }   // 计数器的值   System out println(counter getCount());   }   }   class MyThread implements Runnable   {   private Counter counter;   private CountDownLatch countDownLatch;   public MyThread(Counter counter CountDownLatch countDownLatch)   {   unter = counter;   untDownLatch = countDownLatch;   }   public void run()   {   // 每个线程向Counter中进行 次累加   for(int i = ; i < ; i++)   {   counter addCount();   }   // 完成一个子线程   untDown();   }   }   class Counter   {   private int count = ;   public int getCount()   {   return count;   }   public void addCount()   {   count++;   }   }   public class Main   {   public static void main(String[] args)   {   // 进行 次测试   for(int i = ; i < ; i++)   {   test();   }   }   public static void test()   {   // 计数器   Counter counter = new Counter();   // 线程数量( )   int threadCount = ;   // 用来让主线程等待threadCount个子线程执行完毕   CountDownLatch countDownLatch = new CountDownLatch(threadCount);   // 启动threadCount个子线程   for(int i = ; i < threadCount; i++)   {   Thread thread = new Thread(new MyThread(counter countDownLatch));   thread start();   }   try   {   // 主线程等待所有子线程执行完成 再向下执行   countDownLatch await();   }   catch (InterruptedException e)   {   e printStackTrace();   }   // 计数器的值   System out println(counter getCount());   }   }   class MyThread implements Runnable   {   private Counter counter;   private CountDownLatch countDownLatch;   public MyThread(Counter counter CountDownLatch countDownLatch)   {   unter = counter;   untDownLatch = countDownLatch;   }   public void run()   {   // 每个线程向Counter中进行 次累加   for(int i = ; i < ; i++)   {   counter addCount();   }   // 完成一个子线程   untDown();   }   }   class Counter   {   private int count = ;   public int getCount()   {   return count;   }   public void addCount()   {   count++;   }   }   上面的测试代码中 开启 个线程 每个线程对计数器进行 次累加 最终输出结果应该是   但是上面代码中的Counter未进行同步控制 所以非线程安全   输出结果                                 稍加修改 把Counter改成线程安全的计数器   [java]   class Counter   {   private int count = ;   public int getCount()   {   return count;   }   public synchronized void addCount()   {   count++;   }   }   class Counter   {   private int count = ;   public int getCount()   {   return count;   }   public synchronized void addCount()   {   count++;   }   }   上面只是在addCount()方法中加上了synchronized同步控制 就成为一个线程安全的计数器了 再执行程序   输出结果                            lishixinzhi/Article/program/Java/gj/201311/27519
2023-07-24 20:06:321

java 哪个锁是非重入的

不可重入锁,与可重入锁相反,不可递归调用,递归调用就发生死锁。看到一个经典的讲解,使用自旋锁来模拟一个不可重入锁,代码如下import java.util.concurrent.atomic.AtomicReference;public class UnreentrantLock {private AtomicReference<Thread> owner = new AtomicReference<Thread>();public void lock() {Thread current = Thread.currentThread();//这句是很经典的“自旋”语法,AtomicInteger中也有for (;;) {if (!owner.compareAndSet(null, current)) {return;}}}public void unlock() {Thread current = Thread.currentThread();owner.compareAndSet(current, null);}}代码也比较简单,使用原子引用来存放线程,同一线程两次调用lock()方法,如果不执行unlock()释放锁的话,第二次调用自旋的时候就会产生死锁,这个锁就不是可重入的,而实际上同一个线程不必每次都去释放锁再来获取锁,这样的调度切换是很耗资源的。
2023-07-24 20:06:542

SpringBoot整合Redisson

Redisson的Github地址: https://github.com/redisson/redisson/wiki/Table-of-Content 基于Redis的Redisson分布式可重入锁RLock对象实现了java.util.concurrent.locks.Lock接口。 大家都知道,如果负责储存这个分布式锁的Redisson节点宕机以后,而且这个锁正好处于锁住的状态时,这个锁会出现锁死的状态。为了避免这种情况的发生,Redisson内部提供了一个 监控锁的看门狗 ,它的作用是在Redisson实例被关闭前,不断的延长锁的有效期。默认情况下,看门狗的检查锁的超时时间是30秒钟,也可以通过修改Config.lockWatchdogTimeout来另行指定。 在RedissonLock类的renewExpiration()方法中,会启动一个定时任务每隔30/3=10秒给锁续期。如果业务执行期间,应用挂了,那么不会自动续期,到过期时间之后,锁会自动释放。 另外Redisson还提供了leaseTime的参数来指定加锁的时间。超过这个时间后锁便自动解开了。 如果指定了锁的超时时间,底层直接调用lua脚本,进行占锁。如果超过leaseTime,业务逻辑还没有执行完成,则直接释放锁,所以在指定leaseTime时,要让leaseTime大于业务执行时间。RedissonLock类的tryLockInnerAsync()方法 分布式可重入读写锁允许同时有多个读锁和一个写锁处于加锁状态。在读写锁中,读读共享、读写互斥、写写互斥。 读写锁测试类,当访问write接口时,read接口会被阻塞住。 Redisson的分布式信号量与的用法与java.util.concurrent.Semaphore相似 现在redis中保存semaphore的值为3 然后在TestController中添加测试方法: 当访问acquireSemaphore接口时,redis中的semaphore会减1;访问releaseSemaphore接口时,redis中的semaphore会加1。当redis中的semaphore为0时,继续访问acquireSemaphore接口,会被阻塞,直到访问releaseSemaphore接口,使得semaphore>0,acquireSemaphore才会继续执行。 CountDownLatch作用:某一线程,等待其他线程执行完毕之后,自己再继续执行。 在TestController中添加测试方法,访问close接口时,调用await()方法进入阻塞状态,直到有三次访问release接口时,close接口才会返回。
2023-07-24 20:07:111

java 静态内部匿名类中为什么可以应用this关键字,且引用的this指代什么?

1、当在匿名类中用this时,这个this则指的是匿名类或内部类本身。2、this.i=i 是指 当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)
2023-07-24 20:07:191

Java 怎么在Main函数中,执行完异步任务后才退出主线程

你能说下目的吗。可以加个navtice变量,子线程完成后设为true, 主线程加个while循环,当这个变更为true时,结束循环,也就自动结束了
2023-07-24 20:07:283

java如何在多线程执行完后才执行其他任务

设置一个计数器,每个线程执行完后计数器加一然后查看计数器是否已满(任务都完成),没有的话就阻塞,是的话就唤醒其他所有线程,大家一起来执行下一次任务。要注意公用的计数器的线程安全!
2023-07-24 20:08:334

C# 如何控制子线程运行结束后再运行主线程

java 有一个CountDownLatch类,是专门处理这种问题的。.net好像没有这样的类,你搜一下.net CountDownLatch,然后会出现模拟这个类的一些代码。原理基本上就是一开始定义一个CountDownLatch计数器,比如你有两个子线程,那么这个计数器就为2,然后每个子线程执行完之后,计数器-1,直到到0位置,两个子线程外面需要用 await()方法来阻塞,这样当计数器为0的时候,主线程就能继续执行了。我在java里写的代码,你可以参照网上的例子模拟一个CountDownLatch类。final CountDownLatch lock = new CountDownLatch(1);//验证文件服务器是否运行是否正常new Thread(new Runnable() { public void run() { startCheck(lock); } }).start();lock.await();等待//主线程继续执行startCheck方法里边如果执行完了之后,只需要调用lock.countDown();就行了。
2023-07-24 20:09:562

httpasyncclient异步提交post时,运行2分钟就变得很慢,该怎么解决

public static void main(String[] args) throws Exception { ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); cm.setMaxTotal(100); CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.custom().setConnectionManager(cm).build(); httpAsyncClient.start(); String[] urisToGet = { "http://www.chinaso.com/", "http://www.so.com/", "http://www.qq.com/", }; final CountDownLatch latch = new CountDownLatch(urisToGet.length); for (final String uri: urisToGet) { final HttpGet httpget = new HttpGet(uri); httpAsyncClient.execute(httpget, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.out.println(httpget.getRequestLine() + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(httpget.getRequestLine() + " cancelled"); } }); } latch.await();
2023-07-24 20:10:042

快速学习jav的方法有哪些?

学习没有捷径,但要有好的方法提高效率
2023-07-24 20:10:132

jdk1.7和jdk1.8区别

1、jdk1.8广义上来说,可以说是1.7的增强版,即1.8的功能更加强大,如:1.8中Switch语句支持string类型 、 Try-with-resource语句 、5 数字类型的下划线表示 更友好的表示方式、在可变参数方法中传递非具体化参数,改进编译警告和错误 ;这个太多了,2、 需要注意的是,你用1.8版本开发的程序如果换到其余的1.7版本下可能会报错,即无法运行,而1.7版本下开发的程序,在1.8版本下应该可以正常的运行。 因为版本是自上而下兼容,而自下而上,可能会出问题3、所以建议在真正的开发过程中建议使用1.6或1.7版本(1.8还不是很普遍)
2023-07-24 20:10:234

如何解决java接口访问ZooKeeper时的connectionloss错误

常见错误日志如下:org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss1. 原因:是因为ZooKeeper建立连接时采用异步操作,连接操作后并不能保证ZK连接已成功。如果在ZK连接成功前的这个小时间窗口去访问ZK,就会碰到如上错误。2. 解决思路我们在新建ZK连接后要等一段时间,保证连接成功后再访问ZK。3. 网上比较赞同的解决方案:主要利用两个Java类:(1)java.util.concurrent.CountDownLatch:一个同步辅助类,类似倒数计数,直到计数器为0时才能对资源“解锁”。未解锁前等待该资源的进程只能被阻塞。主要方法:public CountDownLatch(int count); /* 构造函数,参数指定计数次数 */public void countDown(); /* 当前线程调用此函数,则计数减一 */public void await() throws InterruptedException; /* 此函数会一直阻塞当前线程,直到计时器的值为0为止 */(2)org.apache.zookeeper.WatcherZooKeeper有一个很有用的功能,就是集群上每一个变化都可以通知到自定义的Watchcer。
2023-07-24 20:10:401

Java 怎么在Main函数中,执行完异步任务后才退出主线程

你能说下目的吗。可以加个navtice变量,子线程完成后设为true,主线程加个while循环,当这个变更为true时,结束循环,也就自动结束了
2023-07-24 20:10:472

5种方法,教你判断线程池是否全部完成

最近写小玩具的时候用到了 CountDownLatch 计数器,然后顺便想了想判断线程池全部结束有多少种方法。 在网上搜了下,可能有些没找到,但是我找到的有(所有方法都是在 ThreadPoolExecutor 线程池方法下测试的): 好嘞,现在开始一个一个介绍优缺点和简要原理; 先创建一个 static 线程池,后面好几个例子就不一一创建了,全部用这个就行了: 然后再准备一个通用的睡眠方法: 这个方法就是为了测试的时候区分线程执行完毕的下顺序而已。 好嘞,准备完毕,现在开始。 首先贴上测试代码: 这一种方式就是在主线程中进行循环判断,全部任务是否已经完成。 这里有两个主要方法: 通俗点讲,就是在执行全部任务后,对线程池进行 shutdown() 有序关闭,然后循环判断 isTerminated() ,线程池是否全部完成。 类似方法扩展: 还是一样,贴上代码: 还是一样在主线程循环判断,主要就两个方法: 这个好理解,总任务数等于已完成任务数,就表示全部执行完毕。 其他 : 最后扯两句,因为我用 main 方法运行的,跑完后 main 没有结束,是因为非守护线程如果不终止,程序是不会结束的。而线程池 Worker 线程里写了一个死循环,而且被设置成了非守护线程。 这种方法是我比较常用的方法,先看代码: 这种方法,呃,应该是看起来比较高级的,我也不知道别的大佬怎么写的,反正我就用这个。 这个方法需要介绍下这个工具类 CountDownLatch 。先把这种方式的优缺点写了,后面再详细介绍这个类。 CountDownLatch 是 JDK 提供的一个同步工具,它可以让一个或多个线程等待,一直等到其他线程中执行完成一组操作。 常用的方法有 countDown 方法和 await 方法, CountDownLatch 在初始化时,需要指定用给定一个整数作为计数器。 当调用 countDown 方法时,计数器会被减1;当调用 await 方法时,如果计数器大于0时,线程会被阻塞,一直到计数器被 countDown 方法减到0时,线程才会继续执行。 计数器是无法重置的,当计数器被减到0时,调用 await 方法都会直接返回。 这种方式其实和 CountDownLatch 原理类似。 先维护一个静态变量 然后在线程任务结束时,进行静态变量操作: 其实就是加锁计数,循环判断。 Future 是用来装载线程结果的,不过,用这个来进行判断写代码总感觉怪怪的。 因为 Future 只能装载一条线程的返回结果,多条线程总不能用 List 在接收 Future 。 这里就开一个线程做个演示: 这种方式就不写优缺点了,因为 Future 的主要使用场景并不是用于判断任务执行状态。
2023-07-24 20:10:541

java多线程模拟多用户同时查询数据库,计算查询时间。为什么线程跑完后,执行不到t2这部来,无异常显示。

t2这部分不会被运行了countDownLatch 根本就没有执行过countDown的调用你可以首先把countDown变成类的静态成员变量,或者把countDown作为参数带入到类Calc 中,在run方法结束的时候执行countDownLatch.countDown();如果不执行countDownLatch.countDown();操作,计数器不会产生变化,线程跑完了以后程序就停在countDownLatch.await(); 傻等着了........
2023-07-24 20:11:011

怎么在main方法里中断其他线程

要实现这个情况,必须知道以下几点1、java中线程的结束是由run方法运行完成后自动结束的2、在main线程(主线程)中,需要得到所有线程的引用。3、知道jdk提供的CountDownLatch的用法例子如下:public static void main(String[] args) throws InterruptedException {//CountDownLatch作为计数器纪录有几个线程,例如有2个线程CountDownLatch latch=new CountDownLatch(2);Worker worker1=new Worker( latch);Worker worker2=new Worker(latch);worker1.start();// 启动线程worker2.start();////等待所有工人完成工作latch.await();System.out.println("all work done at "+sdf.format(new Date()));} class Worker extends Thread{private CountDownLatch latch;public Worker(CountDownLatch latch){this.latch = latch;}public void run(){xxxxx//在run方法结束之前,讲线程计数器减一latch.countDown();}}
2023-07-24 20:11:201

如何等待java线程池中所有任务完成

用java.util.concurrent下面的类实现线程池就可以
2023-07-24 20:11:281

如何确保main()方法所在的线程是Java程序最后结束的线程?

可以使用Thread类的joint()方法来确保所有程序创建的线程在main()方法退出前结束。可以多了解一些关于Thread类的joint()方法。
2023-07-24 20:11:372

java countdownlatch可以重复使用吗

是线程安全的,这个类设计的目的就是多线程直接的同步合作。试想,如果它不是线程安全的,那岂不是错误的实现~无论有几个线程在操作countdownlatch实例,调用countdownlatch.await()的线程A会被阻塞,除非其他线程BCD...调用countdownlatch.countdown()并且计数器至0.你可以参考这个回答:
2023-07-24 20:11:441

Java中的main线程是不是最后一个退出的线程

这未必的~~~
2023-07-24 20:11:522

main线程结束,子线程为什么没有退出

要实现这个情况,必须知道以下几点1、java中线程的结束是由run方法运行完成后自动结束的2、在main线程(主线程)中,需要得到所有线程的引用。3、知道jdk提供的CountDownLatch的用法例子如下:public static void main(String[] args) throws InterruptedException { //CountDownLatch作为计数器纪录有几个线程,例如有2个线程CountDownLatch latch=new CountDownLatch(2);Worker worker1=new Worker( latch); Worker worker2=new Worker(latch); worker1.start();// 启动线程worker2.start();// //等待所有工人完成工作 latch.await();System.out.println("all work done at "+sdf.format(new Date())); } class Worker extends Thread{private CountDownLatch latch;public Worker(CountDownLatch latch){this.latch = latch;}public void run(){xxxxx//在run方法结束之前,讲线程计数器减一latch.countDown();}}
2023-07-24 20:11:591

java 中有两个线程怎样等待一个线程执行完毕

观公孙大娘弟子舞剑器行(杜甫)[6]
2023-07-24 20:12:063

java如何在多线程执行完成后再执行某个方法

java.util.concurrent.CountDownLatch 这个类可以实现你所要的功能例如:CountDownLatch latch = new CountDownLatch(5) //声明计数器为5个Thread t = new Thread() {public void run() {try {//TODO 你的应用} catch (Exception e) {//TODO 异常处理}finally {latch.countDown(); //这句是关键System.out.println("ok"); //5个线程都跑完后输出}}};t.start();然后让以上操作循环五次(就是说同时开5个线程),那么这个"ok"就会在等到这5个线程都ok后才会被输出一次。
2023-07-24 20:12:281

如何在Main函数中,执行完异步任务后才退出主线程

要实现这个情况,必须知道以下几点1、java中线程的结束是由run方法运行完成后自动结束的2、在main线程(主线程)中,需要得到所有线程的引用。3、知道jdk提供的CountDownLatch的用法例子如下:public static void main(String[] args) throws InterruptedException { //CountDownLatch作为计数器纪录有几个线程,例如有2个线程CountDownLatch latch=new CountDownLatch(2);Worker worker1=new Worker( latch); Worker worker2=new Worker(latch); worker1.start();// 启动线程worker2.start();// //等待所有工人完成工作 latch.await();System.out.println("all work done at "+sdf.format(new Date())); } class Worker extends Thread{private CountDownLatch latch;public Worker(CountDownLatch latch){this.latch = latch;}public void run(){xxxxx//在run方法结束之前,讲线程计数器减一latch.countDown();}}
2023-07-24 20:12:351

如何解决java接口访问ZooKeeper时的connectionloss错误

常见错误日志如下:org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss1. 原因:是因为ZooKeeper建立连接时采用异步操作,连接操作后并不能保证ZK连接已成功。如果在ZK连接成功前的这个小时间窗口去访问ZK,就会碰到如上错误。2. 解决思路我们在新建ZK连接后要等一段时间,保证连接成功后再访问ZK。3. 网上比较赞同的解决方案: 主要利用两个Java类: (1)java.util.concurrent.CountDownLatch: 一个同步辅助类,类似倒数计数,直到计数器为0时才能对资源“解锁”。未解锁前等待该资源的进程只能被阻塞。 主要方法: public CountDownLatch(int count); /* 构造函数,参数指定计数次数 */ public void countDown(); /* 当前线程调用此函数,则计数减一 */ public void await() throws InterruptedException; /* 此函数会一直阻塞当前线程,直到计时器的值为0为止 */ (2)org.apache.zookeeper.Watcher ZooKeeper有一个很有用的功能,就是集群上每一个变化都可以通知到自定义的Watchcer。
2023-07-24 20:12:421

AQS共享锁和独占锁

本文使用 ReentrantLock 和 CountDownLatch 演示独占锁和共享锁的实现。 独占锁 获取锁 释放锁 共享锁 通过status标识锁 ReentrantLock使用排他锁。AQS的status>0表示加锁,thread是当前获取锁的线程。该锁时可重入锁,所以status>0。 CountDownLatch 使用共享锁。AQS的status为共享锁的标记位,status>0就是加锁,等于0就是释放锁。每调用一次countDown(),status减1。 线程会阻塞在await(),直到countDown()将status置为0
2023-07-24 20:12:511

java主线程无线循环判断为什么要sleep?

你可以百度搜一下sleep(0),道理一样
2023-07-24 20:13:008

如何实现java主线程等待子线程执行完毕之后再执行

java.util.concurrent.CountDownLatch 这个类可以实现你所要的功能例如:CountDownLatch latch = new CountDownLatch(5) //声明计数器为5个Thread t = new Thread() {public void run() {try {//TODO 你的应用} catch (Exception e) {//TODO 异常处理}finally {latch.countDown(); //这句是关键System.out.println("ok"); //5个线程都跑完后输出}}};t.start();然后让以上操作循环五次(就是说同时开5个线程),那么这个"ok"就会在等到这5个线程都ok后才会被输出一次。
2023-07-24 20:13:171

java来调和线程轮询的区别

可以使用CountDownLatch, 设定线程数量,然后在每个线程完成的是,latch.countDown()在轮询主线程中使用latch.await(), 这个函数会等待所有线程执行完成后继续允许,即你在轮询前记录一个时间,latch.await() 后面记录完成时间
2023-07-24 20:13:491

c++请求netty为什么没反应

public class SyncFuture<T> implements Future<T> { // 因为请求和响应是一一对应的,因此初始化CountDownLatch值为1。 private CountDownLatch latch = new CountDownLatch(1); // 需要响应线程设置的响应结果 private T response; // Futrue的请求时间,用于计算Future是否超时 private long beginTime = System.currentTimeMillis(); public SyncFuture() { } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { if (response != null) { return true; } return false; } // 获取响应结果,直到有结果才返回。 @Override public T get() throws InterruptedException { latch.await(); return this.response; } // 获取响应结果,直到有结果或者超过指定时间就返回。 @Override public T get(long timeout, TimeUnit unit) throws InterruptedException { if (latch.await(timeout, unit)) { return this.response; } return null; } // 用于设置响应结果,并且做countDown操作,通知请求线程 public void setResponse(T response) { this.response = response; latch.countDown(); } public long getBeginTime() { return beginTime; }}
2023-07-24 20:13:571

调用test方法 只需要3毫秒 而是用现成去执行 有时候 要需要 5毫秒,用多线程去执行 不是应该更快吗?

多线程,并不能使一个方法执行得更快,只是可以“并发”让多个任务同步干活,是整体上快了。
2023-07-24 20:14:041

sparkstreaming结果可以直接flume汇总吗

首先,需要将以下代码编译成jar包,然后在flume中使用,代码转自这里 (如果发现需要依赖的工具类神马的,请在相同目录下的scala文件中找一找) package org.apache.spark.streaming.flume.sinkimport java.net.InetSocketAddressimport java.util.concurrent._import org.apache.avro.ipc.NettyServerimport org.apache.avro.ipc.specific.SpecificResponderimport org.apache.flume.Contextimport org.apache.flume.Sink.Statusimport org.apache.flume.conf.{Configurable, ConfigurationException}import org.apache.flume.sink.AbstractSink/** * A sink that uses Avro RPC to run a server that can be polled by Spark"s * FlumePollingInputDStream. This sink has the following configuration parameters: * * hostname - The hostname to bind to. Default: 0.0.0.0 * port - The port to bind to. (No default - mandatory) * timeout - Time in seconds after which a transaction is rolled back, * if an ACK is not received from Spark within that time * threads - Number of threads to use to receive requests from Spark (Default: 10) * * This sink is unlike other Flume sinks in the sense that it does not push data, * instead the process method in this sink simply blocks the SinkRunner the first time it is * called. This sink starts up an Avro IPC server that uses the SparkFlumeProtocol. * * Each time a getEventBatch call comes, creates a transaction and reads events * from the channel. When enough events are read, the events are sent to the Spark receiver and * the thread itself is blocked and a reference to it saved off. * * When the ack for that batch is received, * the thread which created the transaction is is retrieved and it commits the transaction with the * channel from the same thread it was originally created in (since Flume transactions are * thread local). If a nack is received instead, the sink rolls back the transaction. If no ack * is received within the specified timeout, the transaction is rolled back too. If an ack comes * after that, it is simply ignored and the events get re-sent. * */class SparkSink extends AbstractSink with Logging with Configurable { // Size of the pool to use for holding transaction processors. private var poolSize: Integer = SparkSinkConfig.DEFAULT_THREADS // Timeout for each transaction. If spark does not respond in this much time, // rollback the transaction private var transactionTimeout = SparkSinkConfig.DEFAULT_TRANSACTION_TIMEOUT // Address info to bind on private var hostname: String = SparkSinkConfig.DEFAULT_HOSTNAME private var port: Int = 0 private var backOffInterval: Int = 200 // Handle to the server private var serverOpt: Option[NettyServer] = None // The handler that handles the callback from Avro private var handler: Option[SparkAvroCallbackHandler] = None // Latch that blocks off the Flume framework from wasting 1 thread. private val blockingLatch = new CountDownLatch(1) override def start() { logInfo("Starting Spark Sink: " + getName + " on port: " + port + " and interface: " + hostname + " with " + "pool size: " + poolSize + " and transaction timeout: " + transactionTimeout + ".") handler = Option(new SparkAvroCallbackHandler(poolSize, getChannel, transactionTimeout, backOffInterval)) val responder = new SpecificResponder(classOf[SparkFlumeProtocol], handler.get) // Using the constructor that takes specific thread-pools requires bringing in netty // dependencies which are being excluded in the build. In practice, // Netty dependencies are already available on the JVM as Flume would have pulled them in. serverOpt = Option(new NettyServer(responder, new InetSocketAddress(hostname, port))) serverOpt.foreach(server => { logInfo("Starting Avro server for sink: " + getName) server.start() }) super.start() } override def stop() { logInfo("Stopping Spark Sink: " + getName) handler.foreach(callbackHandler => { callbackHandler.shutdown() }) serverOpt.foreach(server => { logInfo("Stopping Avro Server for sink: " + getName) server.close() server.join() }) blockingLatch.countDown() super.stop() } override def configure(ctx: Context) { import SparkSinkConfig._ hostname = ctx.getString(CONF_HOSTNAME, DEFAULT_HOSTNAME) port = Option(ctx.getInteger(CONF_PORT)). getOrElse(throw new ConfigurationException("The port to bind to must be specified")) poolSize = ctx.getInteger(THREADS, DEFAULT_THREADS) transactionTimeout = ctx.getInteger(CONF_TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT) backOffInterval = ctx.getInteger(CONF_BACKOFF_INTERVAL, DEFAULT_BACKOFF_INTERVAL) logInfo("Configured Spark Sink with hostname: " + hostname + ", port: " + port + ", " + "poolSize: " + poolSize + ", transactionTimeout: " + transactionTimeout + ", " + "backoffInterval: " + backOffInterval) } override def process(): Status = { // This method is called in a loop by the Flume framework - block it until the sink is // stopped to save CPU resources. The sink runner will interrupt this thread when the sink is // being shut down. logInfo("Blocking Sink Runner, sink will continue to run..") blockingLatch.await() Status.BACKOFF } private[flume] def getPort(): Int = { serverOpt .map(_.getPort) .getOrElse( throw new RuntimeException("Server was not started!") ) } /** * Pass in a [[CountDownLatch]] for testing purposes. This batch is counted down when each * batch is received. The test can simply call await on this latch till the expected number of * batches are received. * @param latch */ private[flume] def countdownWhenBatchReceived(latch: CountDownLatch) { handler.foreach(_.countDownWhenBatchAcked(latch)) }}/** * Configuration parameters and their defaults. */private[flume]object SparkSinkConfig { val THREADS = "threads" val DEFAULT_THREADS = 10 val CONF_TRANSACTION_TIMEOUT = "timeout" val DEFAULT_TRANSACTION_TIMEOUT = 60 val CONF_HOSTNAME = "hostname" val DEFAULT_HOSTNAME = "0.0.0.0" val CONF_PORT = "port" val CONF_BACKOFF_INTERVAL = "backoffInterval" val DEFAULT_BACKOFF_INTERVAL = 200}   然后在你的streaming中使用如下的代码package org.apache.spark.examples.streaming import org.apache.spark.SparkConfimport org.apache.spark.storage.StorageLevelimport org.apache.spark.streaming._import org.apache.spark.streaming.flume._import org.apache.spark.util.IntParamimport java.net.InetSocketAddress/** * Produces a count of events received from Flume. * * This should be used in conjunction with the Spark Sink running in a Flume agent. See * the Spark Streaming programming guide for more details. * * Usage: FlumePollingEventCount <host> <port> * `host` is the host on which the Spark Sink is running. * `port` is the port at which the Spark Sink is listening. * * To run this example: * `$ bin/run-example org.apache.spark.examples.streaming.FlumePollingEventCount [host] [port] ` */object FlumePollingEventCount { def main(args: Array[String]) { if (args.length < 2) { System.err.println( "Usage: FlumePollingEventCount <host> <port>") System.exit(1) } StreamingExamples.setStreamingLogLevels() val Array(host, IntParam(port)) = args val batchInterval = Milliseconds(2000) // Create the context and set the batch size val sparkConf = new SparkConf().setAppName("FlumePollingEventCount") val ssc = new StreamingContext(sparkConf, batchInterval) // Create a flume stream that polls the Spark Sink running in a Flume agent val stream = FlumeUtils.createPollingStream(ssc, host, port) // Print out the count of events received from this server in each batch stream.count().map(cnt => "Received " + cnt + " flume events." ).print() ssc.start() ssc.awaitTermination() }}
2023-07-24 20:14:131

如何计算 java 轮询线程消耗

可以使用CountDownLatch, 设定线程数量,然后在每个线程完成的是,latch.countDown()在轮询主线程中使用latch.await(), 这个函数会等待所有线程执行完成后继续允许,即你在轮询前记录一个时间,latch.await() 后面记录完成时间
2023-07-24 20:14:561

android countdownlatch能控制主线程吗

oncurrent包里面的CountDownLatch其实可以把它看作一个计数器,只不过这个计数器的操作是原子操作,同时只能有一个线程去操作这个计数器,也就是同时只能有一个线程去减这个计数器里面的值。 CountDownLatch的一个非常典型的应用场景是:有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。假如我们这个想要继续往下执行的任务调用一个CountDownLatch对象的await()方法,其他的任务执行完自己的任务后调用同一个CountDownLatch对象上的countDown()方法,这个调用await()方法的任务将一直阻塞等待,直到这个CountDownLatch对象的计数值减到0为止。
2023-07-24 20:15:151

java 多线程为什么顺序执行

5个人去上厕所,一个个接着进去,每个人都要蹲一分钟才能拉出来,那你说谁会先拉出来?
2023-07-24 20:15:292

java问题 有一个list有1W条数据, 现在我想用多线程不重复的读取list中的数据,要怎么写?

@Slf4jpublic class FixedThreadPool {/** 请求总数**/private static int clientTotal = 100;public static AtomicInteger atomicInteger = new AtomicInteger(0);public static void main(String[] args) throws Exception {ExecutorService executorService = Executors.newFixedThreadPool(10);final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);for (int i = 0; i < clientTotal; i++) { //这里clientTotal你换成你的list的sizeatomicInteger.incrementAndGet();while (atomicInteger.get() > 4){Thread.sleep(10);}executorService.execute(() -> {consoleLog();countDownLatch.countDown();atomicInteger.decrementAndGet();});}countDownLatch.await();executorService.shutdown();log.info("全部执行完毕");}private static void consoleLog(){try {log.info("hello");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}
2023-07-24 20:15:493

java 怎么在一个线程对象访问某类的时候 追加一个任务在其执行完之后执行?

java.util.concurrent.CountDownLatch 这个类可以实现你所要的功能例如:CountDownLatch latch = new CountDownLatch(5) //声明计数器为5个Thread t = new Thread() {public void run() {try {//TODO 你的应用} catch (Exception e) {//TODO 异常处理}finally {latch.countDown(); //这句是关键System.out.println("ok"); //5个线程都跑完后输出}}};t.start();然后让以上操作循环五次(就是说同时开5个线程),那么这个"ok"就会在等到这5个线程都ok后才会被输出一次。
2023-07-24 20:15:571

your tail is not什么意思

your tail is not 你的尾巴不
2023-07-24 20:13:258

请求大神翻译中译英

In Wiley"s life, his ethic values of serious dislocation, a serious split in personality, life"ethical confusion (NIE Zhen Zhao", "the old man and the sea" and the law of the jungle "89). He is "America dream" followers, victims of the commercial law of the jungle. He spent all his life in the pursuit of "America dream", it is the appearance ofbeautiful dream, the Wiley into the tragedy, but also to death also not sober.As Miller said: "for Wiley, only grades, power, success...... It is true -- city roof dazzing glorious reflection in the sky, he thought it was the real star "(84). What is the finalpurpose of life? The most humane life is what? Miller is convinced that this is not onlya person of his confusion, but also with the ordinary meaning of the question: "I think,not only in the United States, but also in the world, a widespread disoriented, peopleon the future of ignorance" (Guo Jide, "an interview with Arthur Miller," 40). Wiley thinkthrough their diligent efforts to become a rich family, liked the husband and father,however, as not to face the true self, unable to cope with the harsh reality, his life was eventually "America dream" destroyed. However, the death of Wiley is not withoutvalue, his death puts an end to his split personality of pain, and eventually made his son had a thoroughly to remould oneself change.Drama "must go to explore the nature of human existence, to find his need is what, so that these needs attention in society, are satisfied" (Miller 123). Miller created the reason why Wiley resonate, because we everyone has his shadow, the moral dilemma of his loneliness, helplessness, hopelessness, infirmity and endless. Miller of the modern and the traditional melt in a furnace, will be the perfect combination oftraditional ethical themes and modern composing techniques, survival predicament and ethical conflicts that the audience in the traditional but also to experience thefeeling of modern people loss of value, moral significance no appeal. He to the ethical issues of recourse, portrayal of social life crisis, profoundly reveals thecommercialization brings to the social ethics and the harm caused by the destruction of human living situation, expressed deep concerns about the author of commercial society people"s spiritual crisis and the ethical construction of deep care
2023-07-24 20:13:261

大相径庭的意思

大相径庭的成语意思可以比喻“相差很远,大不相同”,这个成语中的“径”是小路的意思,“庭”指的是院子。该成语读作“dà xiāng jìng tíng”。    扩展资料   大相径庭的出处和典故   大相径庭这个成语出自于《庄子》,这个成语的故事发生在春秋时期,楚国狂士接舆对肩吾说北海有一座姑射仙山,山上的神仙可以让世界五谷丰登。肩吾认为接舆的话大而无当、大有径庭、不近人情,就对连叔说接舆在吹牛。连叔沉思了一会,对肩吾说接舆的话不一定是没有道理的。   大相径庭的.成语造句   1、调查显示,不同的群体对这个问题的看法大相径庭。   2、我买的这件衣服的买家秀与卖家秀大相径庭,是我意料之中的事情。
2023-07-24 20:13:261

缺少用英语怎么说?

缺几个:...missing
2023-07-24 20:13:265

SIAMDUNK是不是灌蓝高手的意思?

2023-07-24 20:13:304

英语文章翻译

(一段一段弄,然后补充添加)奥林匹克运动会是一个国际性的综合运动会,涵盖各种各样的运动项目。奥运会是最重要的和广受欢迎的国际赛事之一。全世界的体育迷们都在期待着它。今日奥运会的踪迹可以追溯到古希腊的奥林匹克运动会。在古希腊,运动竞赛是为献给宙斯神而举办的一项活动。随着时间的推移,奥运会赛事采取了一种全新的形式。大会从业余性质转向了职业化,并邀请全球众多国家广泛参与。时代的发展变化给奥运会增添了魅力,同时,其商业化的发展也达到了相当大的程度。奥运会最初开始发展时是小型的。而今日,它已是世界上的一项大型赛会,万众瞩目。奥运会每四年在不同的国家来举办,每一个国家都期待着有机会来承办。北京2008年举办了这项赛事,伦敦是2012年。
2023-07-24 20:13:362

Science Citation Index Expanded 是sci吗

算,现在两者已经不区分
2023-07-24 20:13:232

姐姐们的slamdunk火吗

火。《姐姐们的SlamDunk》是综艺节目,《姐姐们的SlamDunk》收视率随著企画女团UNNIES的推出,直线上升,刷新自身的最高纪录,更连续4周获得同时段一位的好成绩。她们所出演的音乐节目视频也突破200万人次点阅,随着热度增高,《姐姐们的SlamDunk》这部综艺节目也火了。
2023-07-24 20:13:221

翻译高手帮我翻译一段话...不要GOOGLE上面直接翻译的...

才十五分?
2023-07-24 20:13:194

迈克尔杰克逊的歌名 中英对照 谢谢 越多越好

s
2023-07-24 20:13:185

帮我起个英文名…追分50

katong
2023-07-24 20:13:1710

英文中expanded form是什么意思?

扩展的形式。
2023-07-24 20:13:113