线程通信
一、线程间通信的条件
1、两个以上的线程访问同一块内存
2、线程同步,关键字 synchronized
二、线程间通信主要涉及的方法
wait(); ----> 用于阻塞进程
notify(); ----> 用于唤醒进程
notifyAll(); ----> 用于唤醒所有进程
三、线程通信的图解
四、线程通信的实例代码
//主线程
public class ThreadMain { public static void main(String[] args) throws InterruptedException {
Buffer buffer = new Buffer(); Thread_one thread_one = new Thread_one(buffer);
thread_one.start(); //启动子线程 Thread.sleep(1000); //主线程睡眠1秒 String name = Thread.currentThread().getName();
System.out.println(name);
buffer.doNotify(); //唤醒子线程
}
}
//要访问的内存区
public class Buffer { //进行包装
public synchronized void doWait() {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void doNotify() {
notify();
}
}
//子线程
public class Thread_one extends Thread{
private Buffer buffer;
public Thread_one(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
//子线程睡眠
buffer.doWait();
//具体操作,显示当前线程名
String name = Thread_one.currentThread().getName();
System.out.println(name);
}
}