黑马程序员技术交流社区

标题: Java多线程之线程间传递数据 [打印本页]

作者: 轻松过关    时间: 2012-11-29 18:56
标题: Java多线程之线程间传递数据

问题一、线程B向线程A中传递了对象的应用,A得到了数据并进行处理,为什么B线程操作该对象,还是该对象在B中赋的值,A中的处理在B中没有结果。
        B线程在执行过程调用了A线程,并将对象引用传递给了A线程,此时A线程被调用,但B线程仍处于运行状态,而A线程处于等待状态,所有A线程对引用的处理还没有开始,当然在B无法调用A处理后的结果。
下面程序用于演示:
public class A implements Runnable{
        StringBuffer str;
        public A(StringBuffer str) {
                this.str=str;
        }

        public static void main(String[] args) throws InterruptedException {
                        StringBuffer str=new StringBuffer();
                        str.append("这是B线程赋值");
                        //此时A虽然被调用但此时还处于等待状态,所以下面的输出语句中Str的值还是空值
                        //线程A被调用还需要一定时间而下面语句执行的时间还来不及让CPU切换线程。
                        new Thread(new A(str)).start();
                        //让主线程B暂停1秒,线程A才会被调用
                        Thread.sleep(1000);
                        System.out.println(str);
        }

        @Override
        public void run() {
                str.append("你好,这是A线程赋值!");
        }

}

作者: 黑马_郑亮新    时间: 2012-11-29 19:44
public class A implements Runnable{
        StringBuffer str;
        public A(StringBuffer str) {
                this.str=str;
        }

        public static void main(String[] args) throws InterruptedException {
                        StringBuffer str=new StringBuffer();
                        new Thread(new A(str)).start();
                        Thread.sleep(10);
                                                str.append("这是B线程赋值");
                        System.out.println(str);
        }

        @Override
        public void run() {
                str.append("你好,这是A线程赋值!");
        }

}


/*结果:你好,这是A线程赋值!,这是B线程赋值*/







public class A implements Runnable{
        StringBuffer str;
        public A(StringBuffer str) {
                this.str=str;
        }

        public static void main(String[] args) throws InterruptedException {
                        StringBuffer str=new StringBuffer();
                        str.append("这是B线程赋值");
                                                new Thread(new A(str)).start();
                                                Thread.sleep(10);
                                               
                        System.out.println(str);
        }

        @Override
        public void run() {
                str.append("你好,这是A线程赋值!");
        }

}

/*结果:这是B线程赋值,--你好,这是A线程赋值!*/




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2