Skip to content

Instantly share code, notes, and snippets.

@visparashar
Created June 11, 2018 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visparashar/c1db85e5cb00651aca8e74931736eb2e to your computer and use it in GitHub Desktop.
Save visparashar/c1db85e5cb00651aca8e74931736eb2e to your computer and use it in GitHub Desktop.
package com.learning;
import java.util.concurrent.CountDownLatch;
public class ThreadArray {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(10);
Thread[] t = new Thread[10];
MyThread[] mt = new MyThread[10];
for(int i =0;i<10;i++) {
mt[i] = new MyThread(latch);
t[i] = new Thread(mt[i]);
t[i].start();
}
try {
latch.await();
System.out.println(latch.getCount());
for(int i =0;i<10;i++) {
mt[i].stop();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyThread implements Runnable{
public volatile boolean exit =true;
CountDownLatch latch ;
public MyThread(CountDownLatch latch) {
// TODO Auto-generated constructor stub
this.latch =latch;
}
@Override
public void run() {
System.out.println("Running Thread "+Thread.currentThread().getName());
latch.countDown();
while(exit) {
// System.out.println("Running Thread "+Thread.currentThread().getName());
}
System.out.println("stoping thread "+Thread.currentThread().getName());
}
public void stop() {
exit=false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment