|
1 | 1 | --- |
2 | 2 | layout: post |
3 | 3 | category : LeetCode |
4 | | -tagline: "垃圾回收知识点" |
5 | | -tags : [面试,Java,笔记,随手记,垃圾回收] |
| 4 | +tagline: "Java并发知识点笔记" |
| 5 | +tags : [面试,Java,笔记,随手记,并发] |
6 | 6 | --- |
7 | 7 | {% include JB/setup %} |
8 | 8 |
|
9 | 9 | <h4>{{page.title}}</h4> |
10 | 10 |
|
11 | | -1. 一般而言,为Null的对象都会被作为垃圾处理,所以将不用的对象显式地设为Null,有利于GC收集器判定垃圾,从而提高了GC的效率。 |
| 11 | +之前腾讯实习面试这道题就没答出来,问有`A B C`三个线程,如何让`B C`先执行完,`A`再执行,终于看到了相关章节,可以用`CountDownLatch`解决。 |
12 | 12 |
|
13 | | -2. 静态变量属于全局变量,不会被GC回收,它们会一直占用内存。 |
| 13 | + //{java} |
| 14 | + package 使用CountDownLatch来控制线程执行的先后顺序; |
| 15 | + |
| 16 | + import java.util.concurrent.CountDownLatch; |
| 17 | + import java.util.concurrent.ExecutorService; |
| 18 | + import java.util.concurrent.Executors; |
| 19 | + |
| 20 | + public class CountDownLatchTest { |
| 21 | + public static void main(String []args) throws InterruptedException |
| 22 | + { |
| 23 | + ExecutorService exec = Executors.newCachedThreadPool(); |
| 24 | + CountDownLatch latch = new CountDownLatch(2); |
| 25 | + exec.execute(new Task(1, latch)); |
| 26 | + exec.execute(new Task(2, latch)); |
| 27 | + latch.await(); |
| 28 | + System.out.println("主线程结束"); |
| 29 | + } |
| 30 | + |
| 31 | + } |
| 32 | + |
| 33 | + class Task implements Runnable |
| 34 | + { |
| 35 | + int id; |
| 36 | + CountDownLatch latch; |
| 37 | + |
| 38 | + public Task(int id, CountDownLatch latch) { |
| 39 | + super(); |
| 40 | + this.id = id; |
| 41 | + this.latch = latch; |
| 42 | + } |
| 43 | + |
| 44 | + @Override |
| 45 | + public void run() { |
| 46 | + System.out.println(id+"开始工作"); |
| 47 | + try { |
| 48 | + Thread.sleep(2000); |
| 49 | + } catch (InterruptedException e) { |
| 50 | + // TODO Auto-generated catch block |
| 51 | + e.printStackTrace(); |
| 52 | + } |
| 53 | + |
| 54 | + System.out.println(id+"工作完成"); |
| 55 | + latch.countDown(); |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +`latch.await()`表示调用线程`latch.await()`阻塞直到`latch.getCount()=0`才开始执行。`latch.countDown()`则是减1。 |
14 | 63 |
|
15 | | -3. JVM什么时候会进行垃圾回收。线程空闲的时候,堆内存不够用的时候。 |
16 | | - |
17 | 64 | //公共父节点,await实现。并行继续学习。垃圾回收。博客。打印简历 |
0 commit comments