我有个程序这样的: 一个线程类,负责执行某些运算,然后把运算的结果返回到主程序,主程序再利用这些结果来运算某些东西.但是现在我遇到一个问题:这个线程类的线程执行需要时间,还没把运算的结果返回的时候.主程序已经调用一个不可以预知的结果,造成我的程序产生无法预料的数据,请问哪位大侠举个例子来解决这个问题

解决方案 »

  1.   

    比如这样
    public class test extends Thread{
    static int i=0;
    public void run(){
    i++;
    try{
    Thread.sleep(1000);
    }catch(Exception e){}
    }

    public static void main (String[] args) {
             test t=new test();
             t.start();
             System.out.println(i);
        }
    }
    怎样修改让他输出1
      

  2.   

    public class test extends Thread {
    static int i = 0; public void run() {
    i++;
    try {
    Thread.sleep(1000);
    synchronized (this) {
               notifyAll();
             }

    } catch (Exception e) {
    }
    } public static void main(String[] args) {
    test t = new test();
    t.start();
    try {
    synchronized (t){
    t.wait();
    }
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(i);
    }
    }这样该可以么?简单的可以使用wait notify,复杂的使用信号灯。