package thread;
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run() {
int x = 0;
while(true){
synchronized(r){
if(r.flag)
try {
r.wait();
} catch (InterruptedException e) { }
else{
if(x==0){
r.name = "mike";
r.sex = "male";
}
else{
r.name = "丽丽";
r.sex = "女女女女女女女";
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
}
class Output implements Runnable{
private Res r ;
Output(Res r){
this.r = r;
}
public void run() {
while(true){
synchronized(r){
if(!r.flag)
try {
r.wait();
} catch (InterruptedException e) {}
else
{
System.out.println(r.name+"......"+r.sex);
r.flag = false;
r.notify();
}
}
}
}
}
public class Demo1 {
/**
* @线程间通信
* 其实就是多个线程在操作同一个资源,但是操作的动作不同
* 交替输出,可直接运行
*
*/
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Res{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run() {
int x = 0;
while(true){
synchronized(r){
if(r.flag)
try {
r.wait();
} catch (InterruptedException e) { }
else{
if(x==0){
r.name = "mike";
r.sex = "male";
}
else{
r.name = "丽丽";
r.sex = "女女女女女女女";
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
}
class Output implements Runnable{
private Res r ;
Output(Res r){
this.r = r;
}
public void run() {
while(true){
synchronized(r){
if(!r.flag)
try {
r.wait();
} catch (InterruptedException e) {}
else
{
System.out.println(r.name+"......"+r.sex);
r.flag = false;
r.notify();
}
}
}
}
}
线程间通信与多线程并发操作
本文介绍了一种使用Java实现线程间通信和多线程并发操作的方法,通过创建两个线程,一个负责输入数据,另一个负责输出处理后的数据。展示了如何在多个线程中安全地共享资源,利用`synchronized`关键字实现线程同步,并通过`wait()`、`notify()`和`notifyAll()`方法进行线程间的协作。
3855

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



