十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
小编给大家分享一下java多线程wait()和notify()如何使用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

注:wait()和notify()应当用在synchronized内
package com.test;
import java.util.ArrayList;
public class ThreadWaitTeste {
public static void main(String[] args) {
ArrayList ar = new ArrayList();
Product p = new Product(ar);
Consumer c = new Consumer(ar);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Product implements Runnable{
ArrayList array;
public Product(ArrayList array){
this.array= array;
}
public void run() {
while (true){
synchronized(array){
if(this.array.size()<5){
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
this.array.add("test!");
System.out.println("Product size : "+array.size());
}else{
System.out.println("Product wait size : "+array.size()+"数量少于5,等待......");
try {
array.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class Consumer implements Runnable{
ArrayList array;
public Consumer(ArrayList array){
this.array= array;
}
public void run() {
while(true){
synchronized(array){
if(this.array.size()>=5){
this.array.remove(1);
System.out.println("Consumer size : "+array.size());
}else{
try {
array.notifyAll();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} 看完了这篇文章,相信你对“java多线程wait()和notify()如何使用”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联-成都网站建设公司行业资讯频道,感谢各位的阅读!