本帖最后由 NewDemo 于 2014-5-1 15:50 编辑
因为Output类中的run方法没有循环,当然就只能看到一个结果了啊- package day2;
- public class Test0 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- 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();
- }
- }
- /**
- * 1.线程间的通讯:多个线程处理同一资源,但是任务不同
- */
- // TODO Auto-generated method stub
-
- class Res{
- String name;
- String sex;
-
- }
- //输入
- class Input implements Runnable{
- //Res rs=new Res();
- private Res r;
- Input(Res r){ //初始化动作传人要操作的内容
- this.r=r;
- }
- @Override
- public void run() {
-
- int x=0;
- while(true){
- if(x==0){
- r.name="小强";
- r.sex="男";
- }else{
- r.name="小红";
- r.sex="女";
- }
- x=(x+1)%2;
- }
-
- }
- //System.out.println(r.name+"........"+r.sex);
- }
- //输出
- class Output implements Runnable{
- //Res rs=new Res();
- private Res r;
- Output(Res r){ //初始化传人要操作的内容
- this.r=r;
- }
- @Override
- public void run() {
- while(true)
- System.out.println(r.name+"........"+r.sex);//将这句话放进循环里就可以了。
- }
- }
复制代码
因为你的线程没有进行安全性处理,所以肯定出现问题,并不会按照交替打印的,贴上安全处理过的代码- class Res{
- private String name;
- private String sex;
- private boolean flag = false;
- public synchronized void set(String name,String sex){
- if(flag)
- try{this.wait();}catch(Exception e){}
- this.name = name;
-
- this.sex = sex;
- flag = true;
- this.notify()
- }
- public synchronized void out(){
- if(!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(name+"........"+sex);
- flag = false;
- this.notify();
- }
- }
- class Input implements Runnable{
- private Res r ;
- Input(Res r){
- this.r = r;
- }
- public void run(){
- int x = 0;
- while(true){
- if(x==0)
- r.set("mike","man");
- else
- r.set("丽丽","女女女女女");
- x = (x+1)%2;
- }
- }
- }
- class Output implements Runnable{
- private Res r ;
-
- Output(Res r){
- this.r = r;
- }
- public void run(){
- while(true){
- r.out();
- }
- }
- }
复制代码
|