自由发挥,多写写,多探讨探讨新的思路;一些题在目前有很多种解法,各种思路、各种锁
- 这种办法也不完善:因为t1线程release之后不一定是t2线程acquire到,而是有可能还是t1线程acquire到
- 还得结合wait、notify或者await、signal或者CountDownLatch
- 用join规定两线程之间的执行顺序???—->这不就变成单线程顺序执行了吗
- 让t2线程join到t1线程中去
- 还有个问题:就是线程启动start的时候是t2先启动,先拿到semaphore的,t2会先执行完;之后才会去执行t1
- t2线程在t1里面start,然后join—->让t1控制t2,然后join,也可以
- semaphore+join也可以
package com.mashibing.juc.c_020_01_Interview;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Semaphore;import java.util.concurrent.locks.LockSupport;public class T08_Semaphore { // 添加volatile,使t2能够得到通知 volatile List lists = new ArrayList(); public void add(Object o) { lists.add(o); } public int size() { return lists.size(); } static Thread t1 = null, t2 = null; public static void main(String[] args) { T08_Semaphore c = new T08_Semaphore(); Semaphore s = new Semaphore(1); t1 = new Thread(() -> { try { s.acquire(); for (int i = 0; i < 5; i++) { c.add(new Object()); System.out.println("add " + i); } s.release(); } catch (InterruptedException e) { e.printStackTrace(); } try { t2.start(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } try { s.acquire(); for (int i = 5; i < 10; i++) { System.out.println(i); } s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t1"); t2 = new Thread(() -> { try { s.acquire(); System.out.println("t2 结束"); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t2"); //t2.start(); t1.start(); }}
1A2B3C……问题—->linux编程上的一个作业
