Java 线程同步(wait、notify、notifyAll)

一、方法介绍

1、void wait()

使得线程进入等待状态,直到它被其他线程通过notify()或者notifyAll唤醒。该方法只能在同步方法(void synchronized methodName( args... ){ ... })或者 “同步块内部“ (synchronized(object){ ... })被调用。如果当前线程不是锁的持有者,该方法会抛出一个IllegalMonitorStateException异常。

即如果锁住的是object,那么你只能调用object的wait()方法。

2、void notify()

随机选择一个在该对象上调用wait方法的线程,解除其阻塞状态。该方法只能在同步方法(void synchronized methodName( args... ){ ... })或者 “同步块内部“ (synchronized(object){ ... })被调用。如果当前线程不是锁的持有者,该方法会抛出一个IllegalMonitorStateException异常。

3、void notifyAll()

解除所有那些在该对象上调用wait方法的线程的阻塞状态。该方法只能在同步方法(void synchronized methodName( args... ){ ... })或者 “同步块内部“ (synchronized(object){ ... })被调用。如果当前线程不是锁的持有者,该方法会抛出一个IllegalMonitorStateException异常。

二、范例讲解( 注意测试类A只能声明为外部类,下面代码在 class A 和 main方法 之间 省略了MainClass { ... } )

1、“同步块”测试

(1)加synchronized(){}

class A{}
public static void main(String[] args) {
	A object = new A();
	System.out.println("Main Thread Id = " + Thread.currentThread().getId());
	synchronized (object) {
		try {
			System.out.println("This Thread Id = " + Thread.currentThread().getId());
			object.wait();
		} catch (InterruptedException e) {
			</span>e.printStackTrace();
		}
	}
}

输出


(2)不加synchronized(){}

class A{}
public static void main(String[] args) {
	A object = new A();
	System.out.println("Main Thread Id = " + Thread.currentThread().getId());
	//synchronized (object) {
		try {
			</span>System.out.println("This Thread Id = " + Thread.currentThread().getId());
			</span>object.wait();
		} catch (InterruptedException e) {
			</span>e.printStackTrace();
		}
	//}
}
输出如下,L24指的是object.wait()的那行


2、同步方法测试

(1)synchronized方法前缀

class A
{
	public synchronized void test() throws InterruptedException {
		//synchronized (this) {
			System.out.println("Object Thread Id = " + Thread.currentThread().getId());
			wait();
		//}
	};
}
public static void main(String[] args) {
	A object = new A();
	System.out.println("Main Thread Id = " + Thread.currentThread().getId());
	//synchronized (object) {
		try {
			System.out.println("This Thread Id = " + Thread.currentThread().getId());
			//object.wait();
			object.test();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	//}
}

输出


(2)不synchronized方法前缀

class A
{
	public void test() throws InterruptedException {
		//synchronized (this) {
			System.out.println("Object Thread Id = " + Thread.currentThread().getId());
			wait();
		//}
	};
}
public static void main(String[] args) {
	A object = new A();
	System.out.println("Main Thread Id = " + Thread.currentThread().getId());
	//synchronized (object) {
		try {
			System.out.println("This Thread Id = " + Thread.currentThread().getId());
			//object.wait();
			object.test();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	//}
}

输出


3、使用其它锁对象测试

class A{}
public static void main(String[] args) {
	A object = new A();
	Object object2 = new Object();
	System.out.println("Main Thread Id = " + Thread.currentThread().getId());
	synchronized (object) {
	//synchronized (object2) {
		try {
			System.out.println("This Thread Id = " + Thread.currentThread().getId());
			object.wait();
			//object.test();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

输出:


4、wait、notify进行线程同步

(1)一(wait)对一(notify)模式

class A{}
public static void main(String[] args) {
	final A object = new A();
	System.out.println("main thread id = " + Thread.currentThread().getId());
	
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			synchronized (object) {
				try {
					System.out.println("before wait thread id = " + Thread.currentThread().getId());
					object.wait();
					System.out.println("after wait thread id = " + Thread.currentThread().getId());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}).start();
	
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (object) {
				System.out.println("before notify thread id = " + Thread.currentThread().getId());
				object.notify();
				System.out.println("after notify thread id = " + Thread.currentThread().getId());
			}
		}
	}).start();
}

输出

(2)多(wait)对一(notify)模式

class A{}
public static void main(String[] args) {
	final A object = new A();
	System.out.println("main thread id = " + Thread.currentThread().getId());
	
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			synchronized (object) {
				try {
					System.out.println("before wait1 thread id = " + Thread.currentThread().getId());
					object.wait();
					System.out.println("after wait1 thread id = " + Thread.currentThread().getId());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}).start();
	
	new Thread(new Runnable() {
			
			@Override
			public void run() {
				synchronized (object) {
					try {
						System.out.println("before wait2 thread id = " + Thread.currentThread().getId());
						object.wait();
						System.out.println("after wait2 thread id = " + Thread.currentThread().getId());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (object) {
				System.out.println("before notify thread id = " + Thread.currentThread().getId());
				object.notify();
				System.out.println("after notify thread id = " + Thread.currentThread().getId());
			}
		}
	}).start();
}
输出

5、notifyAll

class A{}
public static void main(String[] args) {
	final A object = new A();
	System.out.println("main thread id = " + Thread.currentThread().getId());
	
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			synchronized (object) {
				try {
					System.out.println("before wait1 thread id = " + Thread.currentThread().getId());
					object.wait();
					System.out.println("after wait1 thread id = " + Thread.currentThread().getId());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}).start();
	
	new Thread(new Runnable() {
			
			@Override
			public void run() {
				synchronized (object) {
					try {
						System.out.println("before wait2 thread id = " + Thread.currentThread().getId());
						object.wait();
						System.out.println("after wait2 thread id = " + Thread.currentThread().getId());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (object) {
				System.out.println("before notify thread id = " + Thread.currentThread().getId());
				object.notifyAll();
				System.out.println("after notify thread id = " + Thread.currentThread().getId());
			}
		}
	}).start();
}
输出


三、总结:

(1)由1和2可以看出:object.wait()方法只能在同步方法(void synchronized methodName( args... ){ ... })或者 “同步块内部“ (synchronized(object){ ... })被调用,否则会抛出一个IllegalMonitorStateException异常。

(2)由3可以看出:object.wait()方法只能在锁住自己的情况下被调用,否则会抛出一个IllegalMonitorStateException异常。

(3)由4可得:一个notify只能唤醒一个wait的线程

(4)由5可得:一个notifyAll可以唤醒多个wait的线程

四、注意点:(网上很多博客都讲的不清不楚的,龙神我估计他们就没有花时间真正的去测试过)

wait、notify和notifyAll方法是Object类的final native方法。所以这些方法不能被子类重写,Object类是所有类的超类,因此在程序中有以下三种形式调用wait等方法:

1、wait()

2、this.wait()

3、super.wait()

这三个方法是等价的。


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Java 中,notifynotifyAll 都是用来唤醒等待中的线程的方法。 notify 方法会随机唤醒一个等待中的线程,而 notifyAll 方法则会唤醒所有等待中的线程。 notify 方法通常用于在多线程中共享资源的情况下,当一个线程修改了共享资源之后,通知其他等待中的线程可以重新获取资源并继续执行。但是,如果有多个线程在等待同一个资源,而只有一个线程被唤醒,那么其他线程仍然会继续等待,因此需要使用 notifyAll 方法来唤醒所有等待中的线程。 需要注意的是,notifynotifyAll 方法必须在同步代码块中使用,即在 synchronized 代码块中调用这两个方法。否则会抛出 IllegalMonitorStateException 异常。另外,notifynotifyAll 方法的使用也要谨慎,如果使用不当可能会导致死锁或活锁等问题。 ### 回答2: 在Java中,多线程的notifynotifyAll都是用于线程间的通信。它们都属于Object类的方法,用于唤醒等待在该对象上的线程。 notify方法用于唤醒在该对象上等待的某个线程。当调用notify时,系统将从该对象的等待池中选择一个线程唤醒,被唤醒的线程将进入就绪状态,等待系统调度执行。 notifyAll方法用于唤醒在该对象上等待的所有线程。当调用notifyAll时,系统将唤醒该对象上的所有线程,被唤醒的线程将进入就绪状态,等待系统调度执行。 需要注意的是,notifynotifyAll只能在同步代码块或同步方法中调用,否则会抛出IllegalMonitorStateException异常。这是因为线程在调用notifynotifyAll时必须先获得该对象的锁,才能进行通知操作。 此外,使用notifynotifyAll时需要注意以下几点: 1. 调用notifynotifyAll后,并不会立即释放锁,而是等待同步代码块或同步方法执行完毕后才会释放锁。 2. notify只能唤醒一个线程,选择唤醒的线程是不确定的,而notifyAll会唤醒所有等待的线程。 3. 使用notifynotifyAll时应该慎重,避免因过度唤醒线程导致性能下降或死锁等问题的发生。 总之,通过notifynotifyAll方法,可以实现多个线程之间的协调和通信,实现线程间的同步操作。但是如果使用不当,可能会导致线程安全性和性能问题,因此需要合理地进行调度和使用。 ### 回答3: 在Java中,notifynotifyAll是两种不同的线程通信机制。 notifynotify方法用于唤醒在对象上等待的单个线程。当某个线程调用某个对象的notify方法时,它会唤醒在该对象上等待的单个线程。如果有多个线程等待该对象,但只有一个线程能被唤醒。选择哪个线程被唤醒是不确定的,取决于操作系统的调度机制。 notifyAll:notifyAll方法用于唤醒在对象上等待的所有线程。当某个线程调用某个对象的notifyAll方法时,它会唤醒在该对象上等待的所有线程。这些线程会竞争锁资源,只有一个线程能够获得该对象的锁,并继续执行。 在使用多线程的场景中,notifynotifyAll方法通常与wait方法配合使用实现线程间的通信和协调。wait方法用于使线程等待,并释放该对象的锁,进入该对象的等待池。当其他线程调用notifynotifyAll方法时,等待线程才有可能被唤醒,重新进入该对象的锁池,继续执行。 需要注意的是,notifynotifyAll方法必须在获得相关对象的锁之后调用,否则会抛出IllegalMonitorStateException异常。另外,线程调用notify方法只能唤醒一个等待线程,而调用notifyAll方法能唤醒所有等待线程,但哪个线程能够获得锁资源是不确定的。 因此,在进行线程间通信和协调时,根据具体的需求选择使用notify还是notifyAll方法,并确保在正确的时机、正确的对象上调用这些方法,以实现线程间的正确通信和顺序控制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值