/**
*
* 多线程通讯示例:
* 多线程通讯就是多个线程共同操作同一个资源,但是动作不同
* 例:开启两个线程,交替输入输出两个人的名字和年龄
*
*/
public class ThreadTest
{
public static void main(String[] args)
{
Person p = new Person();
Input in = new Input(p);
Output out = new Output(p);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
//声明一个Person类,有两个属性,姓名和性别
class Person
{
String name;
String sex;
}
//声明一个输入线程继承Runnable。传入名字和性别
class Input implements Runnable
{
private Person p;
Input (Person p)
{
this.p = p;
}
public void run()
{
int x = 0;
while(true)
{
synchronized (p)
{
if (x==0)
{
p.name = "lilei";
p.sex = "boy";
}
else
{
p.name = "hanmeimei";
p.sex = "girl";
}
x = (1+x)%2;
}
}
}
}
//声明一个输出线程的类继承Runnable,输出姓名和性别
class Output implements Runnable
{
private Person p;
Output(Person p)
{
this.p = p;
}
public void run()
{
while(true)
{
synchronized (p)
{
System.out.println("name: "+p.name+"-------sex: "+p.sex);
}
}
}
}
那么问题来了,Input不断输入,Output里面是怎么不断赋值的,赋值代码没有在循环体制内啊,开启线程不是只是run()里面获得和主线程main一样的执行权吗?或者说执行顺序我理解错了?视频看了好几遍都没懂
|