实现一个容器,提供两个方法,add,size。写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5个时,线程2给出提示并结束。
- 用普通线程方法来实现
- 用volitile关键字实现
- 用wait和notify实现
- 使用latch替代wait notify实现
普通线程
public class Exercise318<T> {
private List<T> elements = new ArrayList<>();
private long size = 0;
public void add(T t) {
elements.add(t);
size++;
}
public long size() {
return size;
}
public static void main(String[] args) {
Exercise318 e = new Exercise318();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
e.add(1);
System.out.println(e.size());
}
});
Thread thread2 = new Thread(() -> {
while (true) {
if (e.size() >= 5) {
System.out.println("线程2结束");
break;
}
}
});
thread2.start();
thread1.start();
}
}
wait notify
private List<T> elements = new ArrayList<>();
private long size = 0;
private static Object lock = new Object();
public void add(T t) {
elements.add(t);
size++;
}
public long size() {
return size;
}
public static void main(String[] args) {
Exercise318 e = new Exercise318();
Thread thread1 = new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (e.size() == 5) {
lock.notify();
try {
lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
e.add(1);
System.out.println(e.size());
}
}
});
Thread thread2 = new Thread(() -> {
synchronized (lock) {
if (e.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("线程2结束");
}
lock.notify();
}
});
thread2.start();
thread1.start();
}
}
网友评论