62,614
社区成员
发帖
与我相关
我的任务
分享
package com.demo;
/**
多线程间通讯实例
*/
class Resource
{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name, String sex)
{
if (flag == true)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
}
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out()
{
if (flag != true)
{
try
{
this.wait();
}
catch (InterruptedException e)
{
}
System.out.println(name+"..+.."+sex);
flag = false;
notify();
}
}
}
//=======================================
class Input implements Runnable
{
Resource r;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
System.out.println("in");
if (x == 0)
{
r.set("Mike", "Male");
}
else
{
r.set("丽丽", "女女女女");
}
x =(x + 1) % 2;
}
}
}
//============================================
class Output implements Runnable
{
Resource r;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
System.out.println("out");
r.out();
}
}
}
class ResourceDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}