/**
* @author Alina
* @date 2021年12月22日 12:17 上午
*
*/
class Student{
String name;
String sex;
boolean flag = false;
}
class Product implements Runnable{
Student s ;
Product(Student s ){this.s = s;}
public void run(){
int x = 0;//通过奇数偶数进行赋值
while(true){
synchronized (s){
if(s.flag){
try {
s.wait();
}catch (Exception e){}
}
if (x%2 == 1){
s.name = "张三";
s.sex = "男";
}else {
s.name = "李四";
s.sex = "女";
}
x++;
s.flag = true;
s.notify();
}
}
}
}
class Custom implements Runnable{
Student s;
Custom(Student s ){this.s = s;}
public void run(){
synchronized (s){
while (true){
if(!s.flag){
try{
s.wait();
}catch (Exception e){}
}
System.out.println(s.name+"..."+s.sex);
s.flag = false;
s.notify();
}
}
}
}
public class SourceThreadDemo {
public static void main(String[] args) {
Student s = new Student();
new Thread(new Product(s)).start();
new Thread(new Custom(s)).start();
}
}
(JAVA)多线程之wait()与notify()
最新推荐文章于 2024-08-29 13:45:35 发布