package first;
//定义一个人类,有name 有sex
class Person{
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
//定义生产者,让他实现runnable接口
class Producer implements Runnable{
private Person p;
public Producer(Person p) {
super();
this.p = p;
}
// 让他在构造时携带人的对象
@Override
public void run() {
// TODO Auto-generated method stub
// 一到一千循环,奇数时有一个写入,偶数时有另一个写入
for(int i=0;i<1000;i++)
{
if(1==i%2)
{
p.setName("李先生");
// 中间休眠1毫秒
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.setSex("男");
}
else{
p.setName("王小姐");
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.setSex("女");
}
}
}
}
class Consumer implements Runnable{
private Person p;
public Consumer(Person p) {
super();
this.p = p;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<1000;i++)
{
System.out.println(p.getName()+"-------"+p.getSex());
}
}
}
public class ThreadDemo{
public static void main(String[] args) {
Person p=new Person();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
}
}
|
|