Created
June 11, 2018 07:05
-
-
Save visparashar/c1db85e5cb00651aca8e74931736eb2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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