Created
March 22, 2020 03:59
-
-
Save deepnighttwo/b760bf0bbaddaaf3d3fb6e331684b54d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.TimeUnit; | |
import java.util.stream.IntStream; | |
/** | |
* @author 臧萌 | |
*/ | |
public class PullDataWithTimeLimitAppMain { | |
public static void main(String[] args) throws InterruptedException { | |
long start = System.currentTimeMillis(); | |
CountDownLatch countDownLatch = new CountDownLatch(1); | |
PullDataTask task = new PullDataTask(countDownLatch); | |
new Thread(task).start(); | |
System.out.println("Waiting for data pulling"); | |
countDownLatch.await(10, TimeUnit.SECONDS); | |
System.out.println("Finished waiting. Actually waited for " + (System.currentTimeMillis() - start) / 1000 + " sec. Data got from data puller is " + task.getDataList()); | |
} | |
} | |
class PullDataTask implements Runnable { | |
private List<Integer> dataList = new ArrayList<>(); | |
private CountDownLatch countDownLatch; | |
public PullDataTask(CountDownLatch countDownLatch) { | |
this.countDownLatch = countDownLatch; | |
} | |
@Override | |
public void run() { | |
int timeSec = (int) (Math.random() * 20); | |
System.out.println("going to pulling data for " + timeSec + " seconds"); | |
IntStream.range(0, timeSec).forEach(i -> { | |
try { | |
Thread.sleep(TimeUnit.SECONDS.toMillis(1)); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
dataList.add(i); | |
}); | |
countDownLatch.countDown(); | |
System.out.println("pulling finished"); | |
} | |
public List<Integer> getDataList() { | |
return dataList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment