Demo1 join
//1.现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行
public static void main(String[] args) {
Thread t1=new Thread(
()->{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " t1 is end ");
}
,"t1");
Thread t2=new Thread(
()->{
try {
t1.join();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " t2 is end ");
}
,"t2");
Thread t3=new Thread(
()->{
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " t3 is end ");
}
,"t3");
t1.start();
t2.start();
t3.start();
}
Demo2 线程安全的任务队列
* 使用 wait notify 实现一个队列,队列有2个方法,add 和 get 。
* add方法往队列中添加元素,get方法往队列中获得元素。
* 队列必须是线程安全的。如果get执行时,队列为空,线程必须阻塞等待, 直到有队列有数据。如果add时,队列已经满,则add线程要等待,直到队列有空闲空间。
public class TestDemo2 {
public static void main(String[] args) {
TestQueue<Integer> testQueue=new TestQueue<>(3);
new Thread(
()->{
for (int i = 0 ;; i ++ ){
testQueue.add(i);
}
}
).start();
new Thread(
()->{
while (true)
testQueue.removeFirst();
}
).start();
new Thread(
()->{
while (true)
testQueue.removeFirst();
}
).start();
}
}
public class TestQueue<E> {
private LinkedList<E> linkedList = new LinkedList<E>() ;
private int linkSize ;
private int fullSize = 0 ;
private static Object lock = new Object();
public TestQueue(int fullSize) {
if (fullSize < 0) {
throw new RuntimeException();
}
this.fullSize = fullSize ;
if (fullSize >= Integer.MAX_VALUE) {
this.fullSize = Integer.MAX_VALUE ;
}
}
public boolean add(E e) {
Thread.yield();
synchronized (lock) {
while (linkSize >= fullSize) {
try {
System.out.println("waiting for queue is full and linkSize = " + linkSize);
lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
return false;
}
}
System.out.println( "queue add ");
linkedList.add(e);
linkSize += 1 ;
return true ;
}
}
public E removeFirst() {
synchronized (lock) {
while (linkSize <= 0) {
try {
System.out.println("waiting for queue is empty and linkSize = " + linkSize);
lock.notifyAll();
lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
return null;
}
}
System.out.println( "queue remove ");
E e = linkedList.removeFirst();
linkSize -= 1 ;
return e ;
}
}