This is the java series of 31 high concurrency.
Environment: jdk1.8.
java series of high concurrency has learned a lot, and this article, we use the knowledge learned earlier to implement a demand:
Need to get the results of other threads in a thread, you can think of several ways? What advantages and disadvantages?
Combined with this requirement, we use 6 Ways to do a review of previously learned knowledge, enhance memory.
Mode 1: Thread the join () method implementation
Code:
package com.itsoku.chat31;
import java.sql.Time;
import java.util.concurrent.*;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo1 {
//用于封装结果
static class Result<T> {
T result;
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(System.currentTimeMillis());
//用于存放子线程执行的结果
Result<Integer> result = new Result<>();
//创建一个子线程
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
result.setResult(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
//让主线程等待thread线程执行完毕之后再继续,join方法会让当前线程阻塞
thread.join();
//获取thread线程的执行结果
Integer rs = result.getResult();
System.out.println(System.currentTimeMillis());
System.out.println(System.currentTimeMillis() + ":" + rs);
}
}
Output:
1566733162636
1566733165692
1566733165692:10
Code by blocking the main thread join the current way, when a thread after thread is finished, join methods will continue.
join the way, you can only block a thread if the other threads also need to obtain the results thread thread, join methods do nothing to help.
About join () method and the use of threads in more detail, can refer to: the basic operation of the thread
Mode 2: CountDownLatch achieve
Code:
package com.itsoku.chat31;
import java.util.concurrent.*;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo2 {
//用于封装结果
static class Result<T> {
T result;
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(System.currentTimeMillis());
CountDownLatch countDownLatch = new CountDownLatch(1);
//用于存放子线程执行的结果
Demo1.Result<Integer> result = new Demo1.Result<>();
//创建一个子线程
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
result.setResult(10);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
countDownLatch.countDown();
}
});
thread.start();
//countDownLatch.await()会让当前线程阻塞,当countDownLatch中的计数器变为0的时候,await方法会返回
countDownLatch.await();
//获取thread线程的执行结果
Integer rs = result.getResult();
System.out.println(System.currentTimeMillis());
System.out.println(System.currentTimeMillis() + ":" + rs);
}
}
Output:
1566733720406
1566733723453
1566733723453:10
The above code is also achieved the desired results, use CountDownLatch
can make one or more threads wait for a number of threads after the completion of their own and then continue; CountDownLatch
more detail see: the JUC waiting multithreading tools CountDownLatch completed, the necessary skills
Mode 3: ExecutorService.submit method implementation
Code:
package com.itsoku.chat31;
import java.util.concurrent.*;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建一个线程池
ExecutorService executorService = Executors.newCachedThreadPool();
System.out.println(System.currentTimeMillis());
Future<Integer> future = executorService.submit(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
//关闭线程池
executorService.shutdown();
System.out.println(System.currentTimeMillis());
Integer result = future.get();
System.out.println(System.currentTimeMillis() + ":" + result);
}
}
Output:
1566734119938
1566734119989
1566734122989:10
Using the ExecutorService.submit
method implemented, this method returns a Future
, future.get()
let the current thread to block until the task is completed to perform Future association.
related information:
- JAVA thread pool, this one is enough
- Detailed JUC frame 1 in the Executor
- Detailed JUC frame 2 in the Executor
Mode 4: FutureTask Mode 1
Code:
package com.itsoku.chat31;
import java.util.concurrent.*;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo4 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(System.currentTimeMillis());
//创建一个FutureTask
FutureTask<Integer> futureTask = new FutureTask<>(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
//将futureTask传递一个线程运行
new Thread(futureTask).start();
System.out.println(System.currentTimeMillis());
//futureTask.get()会阻塞当前线程,直到futureTask执行完毕
Integer result = futureTask.get();
System.out.println(System.currentTimeMillis() + ":" + result);
}
}
Output:
1566736350314
1566736350358
1566736353360:10
Used in the code FutureTask
implemented, FutureTask implements Runnable
the interface, and the internal return value, it can be passed to the Thread run directly futureTask.get()
blocks the current thread until the FutureTask
task is completed the implementation of the constructor pass, get method will return. About FutureTask
details, please refer to: Executor framework JUC Comments 1
Mode 5: FutureTask Embodiment 2
Code:
package com.itsoku.chat31;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo5 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(System.currentTimeMillis());
//创建一个FutureTask
FutureTask<Integer> futureTask = new FutureTask<>(() -> 10);
//将futureTask传递一个线程运行
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
futureTask.run();
}).start();
System.out.println(System.currentTimeMillis());
//futureTask.get()会阻塞当前线程,直到futureTask执行完毕
Integer result = futureTask.get();
System.out.println(System.currentTimeMillis() + ":" + result);
}
}
Output:
1566736319925
1566736319970
1566736322972:10
Create an FutureTask
object, call futureTask.get()
will block the current thread, the child thread dormant for three seconds, and then call futureTask.run();
when futureTask the run () method after finished, futureTask.get()
returns from blocking.
Note: in this way and 4 way different points.
About FutureTask
details, please refer to: Executor framework JUC Comments 1
Way 6: CompletableFuture manner
Code:
package com.itsoku.chat31;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* 跟着阿里p7学并发,微信公众号:javacode2018
*/
public class Demo6 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println(System.currentTimeMillis());
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
});
System.out.println(System.currentTimeMillis());
//futureTask.get()会阻塞当前线程,直到futureTask执行完毕
Integer result = completableFuture.get();
System.out.println(System.currentTimeMillis() + ":" + result);
}
}
Output:
1566736205348
1566736205428
1566736208429:10
CompletableFuture.supplyAsync
It can be used to perform asynchronous tasks with a return value, callcompletableFuture.get()
Blocks the current thread until the task is finished, get method will return.
About CompletableFuture
more detailed usage, see: JUC in tools CompletableFuture, essential skills
java series of high concurrency directory
- Day 1: You must know a few concepts
- Day 2: concurrency level
- Day 3: Two important laws of the relevant parallel
- Day 4: JMM related concepts
- Day 5: In-depth understanding of processes and threads
- Basic operation thread: Day 6
- Day 7: volatile and Java Memory Model
- Day 8: Thread Group
- Day 9: user thread and thread guard
- Day 10: thread safe and synchronized keyword
- Day 11: thread interrupted in several ways
- Day 12 JUC: ReentrantLock reentrant lock
- Day 13: JUC Condition objects in
- Day 14: The JUC LockSupport tools, essential skills
- Day 15: Semaphore (semaphore) in JUC
- Day 16: JUC waiting in multithreading tools CountDownLatch completed, the necessary skills
- 17th day: circular fence in CyclicBarrier kinds scene JUC 6
- Day 18: JAVA thread pool, this one is enough
- Day 19: JUC Detailed frame 1 in Executor
- Day 20: JUC Detailed frame 2 in Executor
- Day 21: java in CAS, you need to know
- Day 22: JUC underlying tools Unsafe, master must understand
- Day 23: JUC class atom, an enough
- Day 24: ThreadLocal, InheritableThreadLocal (easy to understand)
- Day 25: JUC grasp of blocking queue
- The first 26: Learn to use a common set of JUC, often look!
- Day 27: actual articles, interfaces, performance times so simple
- Day 28: actual articles, pain micro service logs together to help you get rid of
- Day 29: concurrent high common mode current limit
- Day 30: JUC in tools CompletableFuture, essential skills
Ali p7 concurrent with the school, the public number: passerby java, get the latest articles every day!