线程间通信(线程与线程间进行通信)
线程池:存放等待中的线程的一片空间
等待唤醒机制:
wait(); 让一个线程处于等待,等待线程释放执行权回到线程池当中等待
notify(); 随机唤醒线程池当中的一个线程
notifyAll(); 唤醒线程池当中所有的线程
以上方法都是对象上的方法,都是锁对象上的方法-->锁就相当于是监视该线程上的一个监视器
//学生类
class student {
String name;
String sex;
}
// 输入类
class Input implements Runnable {
private int count;
private student s;
public Input(student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (student.class) { // (s) 反正都是操作同一对象 即也可以 以锁为对象
if (count % 2 == 0) {
s.name = "张三";
s.sex = "男";
} else {
s.name = "lisi";
s.sex = "women";
}
count++;
}
}
}
}
// 输出类
class Output implements Runnable {
private student s;
public Output(student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (student.class) { // (s) 反正都是操作同一对象 即也可以 以锁为对象
System.out.println(s.name + ":" + s.sex);
}
}
}
}
// 线程测试类
public class ThreadDemo03 {
public static void main(String[] args) {
student s = new student();
Input i = new Input(s);
Output o = new Output(s);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
经过优化之后的唤醒机制
//学生类
class Student{
private String name;
private String sex;
private boolean flag = false;
public void set(String name,String sex){
synchronized(this){
if(flag)//如果标记为true,就代表输入已完成,输入任务就可以等待
try {wait();} catch (InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
notify();
}
}
public void show(){
synchronized(this){
if(!flag)
try {wait();} catch (InterruptedException e) {}
System.out.println(this.name + " : " + this.sex);
flag = false;
notify();
}
}
}
//输入类
class Input implements Runnable{
private Student s;
private int count;
public Input(Student s) {
this.s = s;
}
@Override
public void run() {
//要执行的输入任务
while(true){
if(count % 2 == 0){
s.set("张三", "男");
}else{
s.set("lisi", "woman");
}
count++;
}
}
}
//输出类
class Output implements Runnable{
private Student s;
public Output(Student s) {
this.s = s;
}
@Override
public void run() {
//输出的任务
while(true){
s.show();
}
}
}
//测试类
public class ThreadDemo05 {
public static void main(String[] args) {
//创建学生对象
Student s = new Student();
//创建线程任务
Input input = new Input(s);
Output output = new Output(s);
//创建线程
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
//开启线程
t1.start();
t2.start();
}
}