barriers / 阅读 / 详情

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

2023-07-25 12:21:58
TAG: in 方法 ma main
共1条回复
黑桃云

要实现这个情况,必须知道以下几点

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();

}

}

相关推荐

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

如何等待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里有没有类似SLEEP的函数

2023-07-24 20:13:241

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

求一英文名

mario mansson马瑞.曼森
2023-07-24 20:11:2113

一篇关于 the Internet 的英语作文

网上找的The Internet is a standardized, global system of interconnected computer networks that connects millions of people. The system uses the Internet Protocol Suite (TCP/IP) standard rules for data representation, signaling, authentication, and error detection. It is a network of networks that consists of millions of private and public, academic, business, and government networks of local to global scope that are linked by copper wires, fiber-optic cables, wireless connections, and other technologies. The Internet carries a vast array of information resources and services, most notably the inter-linked hypertext documents of the World Wide Web (WWW) and the infrastructure to support electronic mail, in addition to popular services such as video on demand, online shopping, online gaming, exchange of information from one-to-many or many-to-many by online chat, online social networking, online publishing, file transfer, file sharing and Voice over Internet Protocol (VoIP) or teleconferencing, telepresence person-to-person communication via voice and video.The origins of the Internet reach back to the 1960s when the United States funded research projects of its military agencies to build robust, fault-tolerant and distributed computer networks. This research and a period of civilian funding of a new U.S. backbone by the National Science Foundation spawned worldwide participation in the development of new networking technologies and led to the commercialization of an international network in the mid 1990s, and resulted in the following popularization of countless applications in virtually every aspect of modern human life. As of 2009, an estimated quarter of Earth"s population uses the services of the Internet.
2023-07-24 20:11:221

大相径庭的意思及成语解释

大相径庭比喻相差很远,大不相同。径:小路;庭:院子;径庭:悬殊,偏激。成语出处:先秦·庄子及其后学《庄子·逍遥游》:“肩吾问于连叔曰:‘吾闻言于接舆,大而无当,往而不返。吾惊怖其言,犹河汉而无极也;大有径庭,不近人情焉。"”后世据此典故引申出成语“大相径庭”。成语用法:偏正式结构,在句中一般作谓语。成语例句:1、由于我们的观点大相径庭,讨论陷入了僵局。2、语言的发展使得汉语里很多字、词的古今义大相径庭。3、讨论班里事情,他和我的意见常常大相径庭。
2023-07-24 20:11:232

delphi中树控件中,怎样展开当前项?

if assigned(TreeView1.selected) then TreeView1.selected.expanded:=True;
2023-07-24 20:11:243

How soon 和how long , how far的区别

Howlong就是指多长,不管是多长时间还是路程Howfar就是指多远,但是和Howlong的第二个意思还是有些差别的,howfar通常是指具体的距离,这个就要凭语感了Howsoon指多久,用在将来时。soon要与quickly和fast区分,soon指时间,quickly指动作,fast指速度
2023-07-24 20:11:242

tail怎么读

tail[英][teu026al] [美][tel] 生词本简明释义n.尾;尾部;燕尾服;尾随者vt.跟踪;装上尾巴vi.队伍单行行进时拉长或产生间隔;侦察队两两散开;[建筑学] 嵌上,搭上复数:tails第三人称单数:tails过去式:tailed过去分词:tailed现在分词:tailing以下结果由 金山词霸 提供柯林斯高阶英汉词典 百科释义 短语词组 同反义词1.N-COUNT尾;尾巴The tail of an animal, bird, or fish is the part extending beyond the end of its body.The cattle were swinging their tails to disperse the flies.那些牛甩动着尾巴驱赶苍蝇。...a black dog with a long tail.长尾黑狗
2023-07-24 20:11:261

pos是什么意思啊

POS的意思很多,最常见的意思是:销售终端。金融领域中Pos是point of sale的缩写,是指一种多功能终端的销售终端,把它安装在信用卡的特约商户以及受理网点中和计算机联成网络,即可实现电子资金自动转账。它具有支持消费、预授权、余额查询和转账等功能,使用起来安全、快捷、可靠。POS系统基本原理是先将商品资料创建于计算机文件内,透过计算机收银机联机架构,商品上之条码能透过收银设备上光学读取设备直接读入后(或由键盘直接输入代号)马上可以显示商品信息加速收银速度与正确性。每笔商品销售明细资料(售价,部门,时段,客层)自动记录下来,再由联机架构传回计算机。POS的作用POS具有预授权、转账、余额查询等功能,使用起来较为快捷、安全、可靠。POS系统基本原理是把商品资料创建于计算机文件中,透过计算机收银机联机架构,商品上的条码透过收银设备上光学读取设备直接读入或者是直接输入代号后,马上就能显示商品的信息,加快收银的速度和正确性。POS机是通过读卡器读取银行卡上的持卡人磁条中的信息,由POS操作人员输入交易金额,再由持卡人输入银行卡密码,POS就会把这些信息通过银联中心,上送发卡银行系统,完成联机交易,并且给出成功与否的信息,最后打印相应的票据即可。
2023-07-24 20:11:151

用how far造5个句子

How far is the next gas station? How far is it from here to the zoo? How far is canada from france? How far is it from Beijing to Guangzhou? Parallel lines will never meet no matter how far extended. How far does the road continue?
2023-07-24 20:11:141

sci expanded收录期刊是指什么

Science Citation Index Expanded是SCI的扩展版,SCI收录3000余种期刊,以前可以通过光盘或者手工翻阅可以检索。现在整合到Web of Science中,通过网络可以检索,期刊也增加到6000余种,所以称为Science Citation Index Expanded。 关于期刊的问题可以咨询《发表吧》他们比较了解。
2023-07-24 20:11:141

迈克尔杰克逊 德国演唱会【全套歌名】

A:Smile (只在南非的德班演唱) 基辅大门序曲 串烧: "Scream" "They Don"t Care About Us" "She Drives Me Wild/In the Closet" "Wanna Be Startin" Somethin"" "Stranger in Moscow" "Smooth Criminal" (特色:"Mind Is The Magic") "The Wind" 影片插曲 "You Are Not Alone" "The Way You Make Me Feel" (只在1996年9月7日至1997年6月15日的部分演出内表演) 杰克逊五人组歌曲串烧: "I Want You Back" "The Love You Save" "I"ll Be There" Off the Wall专辑串烧: (只在1997年6月10日之前的部分演唱会表演) "Rock with You" "Off the Wall" "Don"t Stop "Til You Get Enough" "Remember the Time" 视频编辑插曲 "Billie Jean" "Thriller" "Beat It" "Come Together" / "D.S." (只在1996年9月7日至1996年11月11日的部分演唱会内表演) "Blood on the Dance Floor" (1997年5月31日至1997年8月19日的演唱会内表演) Black or White "Panther"视频插曲 "Dangerous" (特色:Smooth Criminal和珍妮特·杰克逊的歌曲片段) "Black or White" "Earth Song" "We Are the World" 视频插曲 "Heal the World" "They Don"t Care About Us (工具) "HIStory" (与HIStory on Film的插曲)
2023-07-24 20:11:133

请做过外贸的高手翻译1

General Information 1.1. Name of the product or cosmetic group. 1.2. Cosmetic form; 1.3. Name and address of the manufacturer or the responsible for the commercialization of product, authorized by the manufacturer. 综合信息1。1 产品名称或者化妆品种类1。2化妆品外形1。3产品所属并经过授权的企业地址和名称以后不想翻译了,,
2023-07-24 20:11:132

爱迪生的简介 用英语翻译

Thomas Alva Edisonborn Feb. 11, 1847, Milan, Ohio, U.S.died Oct. 18, 1931, West Orange, N.J.U.S. inventor.He had very little formal schooling. He set up a laboratory in his father"s basement at age 10; at 12 he was earning money selling newspapers and candy on trains. He worked as a telegrapher (1862–68) before deciding to pursue invention and entrepreneurship. Throughout much of his career, he was strongly motivated by efforts to overcome his handicap of partial deafness. For Western Union he developed a machine capable of sending four telegraph messages down one wire, only to sell the invention to Western Union"s rival, Jay Gould, for more than $100,000. He created the world"s first industrial-research laboratory, in Menlo Park, N.J. There he invented the carbon-button transmitter (1877), still used in telephone speakers and microphones today; the phonograph (1877); and the incandescent lightbulb (1879). To develop the lightbulb, he was advanced $30,000 by such financiers as J.P. Morgan and the Vanderbilts. In 1882 he supervised the installation of the world"s first permanent commercial central power system, in lower Manhattan. After the death of his first wife (1884), he built a new laboratory in West Orange, N.J. Its first major endeavour was the commercialization of the phonograph, which Alexander Graham Bell had improved on since Edison"s initial invention. At the new laboratory Edison and his team also developed an early movie camera and an instrument for viewing moving pictures; they also developed the alkaline storage battery. Although his later projects were not as successful as his earlier ones, Edison continued to work even in his 80s. Singly or jointly, he held a world-record 1,093 patents, nearly 400 of them for electric light and power. He always invented for necessity, with the object of devising something new that he could manufacture. More than any other, he laid the basis for the technological revolution of the modern electric world.
2023-07-24 20:11:051