Java基础-线程的通信

来源:互联网 发布:sql delete多个表 编辑:程序博客网 时间:2024/05/16 06:32

线程的通信

实现线程之间的交互

用到的方法

wait()与notify()和notifyAll()
1.wait():令当前线程挂起并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
2.notify():唤醒正在排队等候同步资源的线程中优先级最高者结束等待
notifyAll():唤醒正在排队等待同步资源的所有线程结束等待
Java.lang.Object提供的这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报Java.lang.IllegalMonitorStateException异常

例子

此处插入TestCommunication

/** * 线程通信 * 使用两个线程打印1-100,线程1,线程2,交替打印 * */class PrintNum implements Runnable{int num=1;public void run(){while(true){synchronized (this) {notify();if (num <= 100) {System.out.println(Thread.currentThread().getName() + ":" + num);num++;} else {break;}try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}public class TestCommunication {public static void main(String[] args) {PrintNum p=new PrintNum();Thread t1=new Thread(p);Thread t2=new Thread(p);t1.setName("甲");t2.setName("乙");t1.start();t2.start();}}



0 0