wait和notify方法不是线程对象的方法,是java中任何一个java对象都有的对象,因为这两个方法是Object类中自带的
wait方法的作用:让正在活动的线程进入等待状态,无期限等待,直到被唤醒为止
,这个期间会释放锁
notify方法的作用:唤醒正在等待的线程
notifyall方法的作用:唤醒所有等待的线程
下面直接上代码
代码1:生产者和消费者模式 结果:两个线程生产一个,消费一个
package thread;
import java.util.ArrayList;
import java.util.List;
/*
使用wait方法和notify方法实现生产者和消费者模式
*/
public class ThreadDemo15 {
public static void main(String[] args) {
List list = new ArrayList();
//生产者线程
Thread t1 = new Thread(new Producer(list));
//消费者线程
Thread t2 = new Thread(new Consumer(list));
t1.setName("生产者线程");
t2.setName("消费者线程");
t1.start();
t2.start();
}
}
//生产线程
class Producer implements Runnable{
private List list;
public Producer(List list) {
this.list = list;
}
@Override
public void run() {
//一直生产
while (true){
synchronized (list){
if (list.size() > 0) {
//当先线程进入等待转态
try {
list.wait();//会释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object object = new Object();
list.add(object);
System.out.println(Thread.currentThread().getName()+"--->"+object);
//唤醒消费者进行消费
list.notify();
}
// System.out.println(1);
}
}
}
//消费线程
class Consumer implements Runnable{
private List list;
public Consumer(List list) {
this.list = list;
}
@Override
public void run() {
while (true){
synchronized (list){
if(list.size()==0){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object o = list.remove(0);
System.out.println(Thread.currentThread().getName()+"--->"+o);
//唤醒生产者生产
list.notify();
}
}
}
}
代码2:两个线程相互输出123456789.......
```java
package thread;
public class ThreadDemo16 {
public static void main(String[] args) {
MyResult myResult = new MyResult(0);
Thread t1 = new Thread(new Thread16(myResult));
Thread t2 = new Thread(new Thread17(myResult));
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class MyResult{
int i;
public MyResult(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
class Thread16 implements Runnable{
MyResult myResult;
public Thread16(MyResult myResult){
this.myResult = myResult;
}
@Override
public void run() {
while (true){
synchronized (myResult){
if(myResult.getI()%2==1){
try {
myResult.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = myResult.getI()+1;
myResult.setI(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->"+i);
myResult.notify();
}
}
}
}
class Thread17 implements Runnable{
MyResult myResult;
public Thread17(MyResult myResult){
this.myResult = myResult;
}
@Override
public void run() {
while (true){
synchronized (myResult){
if(myResult.getI()%2==0){
try {
myResult.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = myResult.getI()+1;
myResult.setI(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->"+i);
myResult.notify();
}
}
}
}
结果: