实现目标:两个线程,线程1向list集合装入对象,装入到第5个元素时,线程2输出一句话,再次回到线程1,直到装入10个元素。
1.使用wait(),notify()
(1)首先启动线程2,进入同步代码块,判断list的元素数量,如果不为5,调用wait方法,让出同步锁。
(2)线程1拿到锁,顺序向list集合中放入元素,当集合元素数量达到5时,调用notify方法,调用wait方法(如果不调用wait方法,无法释放锁,将会执行到循环结束)
(3)线程2向下执行,输出一句话,调用notify方法
(4)线程1继续循环
public class WaitNotifyDemo {
List list=Collections.synchronizedList(new ArrayList<>());
Object object=new Object();
//Thread 1
public void add(){
synchronized (this){
System.out.println("T1 start");
for (int i = 0; i <10 ; i++) {
list.add(object);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---"+list.size());
if(list.size()==5){
this.notify();
try {
this.wait();
System.out.println("666666");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//Thread 2
public void get(){
synchronized (this){
System.out.println("T2 start");
if(list.size()!=5){
try {
this.wait();
System.out.println("77777");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread2 listSize is 5");
this.notify();
}
}
public static void main(String[] args) {
WaitNotifyDemo c = new WaitNotifyDemo();
new Thread(()->{
c.get();
},"T2").start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
c.add();
},"T1").start();
}
}
代码执行结果
T2 start
T1 start
T1---1
T1---2
T1---3
T1---4
T1---5
77777
Thread2 listSize is 5
666666
T1---6
T1---7
T1---8
T1---9
T1---10
2.使用LockSupport的part和unpart方法
1.首先启动线程2,执行到park方法,进入阻塞状态
2.启动线程1进入循环,判断list.size()=5,执行unpark方法,使线程2启动,执行park方法,阻塞线程1
3.线程2输出一句话,执行unpark方法,使线程1继续执行
public class LockSupportDemo {
List list=Collections.synchronizedList(new ArrayList());
Object lock=new Object();
static Thread t2;
static Thread t1;
//线程1
public void add(){
System.out.println("T1 start");
for (int i = 0; i <10 ; i++) {
list.add("11");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---"+list.size());
if (list.size()==5){
LockSupport.unpark(t2);
LockSupport.park();
}
}
}
//线程2
public void get(){
System.out.println("T2 start");
LockSupport.park();
System.out.println("Thread2 found size is 5 ");
LockSupport.unpark(t1);
}
public static void main(String[] args) {
LockSupportDemo c = new LockSupportDemo();
t2=new Thread(()->{
c.get();
});
t1=new Thread(()->{
c.add();
});
t2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
}
}
代码执行结果
T2 start
T1 start
Thread-1---1
Thread-1---2
Thread-1---3
Thread-1---4
Thread-1---5
Thread2 found size is 5
Thread-1---6
Thread-1---7
Thread-1---8
Thread-1---9
Thread-1---10