package thread;
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
while(flag)
try {this.wait();} catch (InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try {this.wait();} catch (InterruptedException e) {}
System.out.println(name+".........."+sex);
flag = false;
this.notifyAll();
}
}
class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("lily", "female");
else
r.set("李明明", "男男男男男男男");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Res r = new Res();
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){
while(flag)
try {this.wait();} catch (InterruptedException e) {}
this.name = name;
this.sex = sex;
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try {this.wait();} catch (InterruptedException e) {}
System.out.println(name+".........."+sex);
flag = false;
this.notifyAll();
}
}
class Input implements Runnable{
Res r = new Res();
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x==0)
r.set("lily", "female");
else
r.set("李明明", "男男男男男男男");
x = (x+1)%2;
}
}
}
class Output implements Runnable{
Res r = new Res();
Output(Res r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
本文提供了一个关于线程间通信的示例程序,通过两个线程分别进行输入和输出操作来实现同步交互,展示了如何使用Java的synchronized关键字及wait、notify方法来确保线程间的正确通信。
1021

被折叠的 条评论
为什么被折叠?



