我编了一个程序,是两个人一人抽10次数(0-50),A抽一次B抽一次,要求同步,每抽一轮,比较两个人抽的数的大小,两个人各一个线程。
我用两个线程已经作到了同步,但是怎么在第二个人抽了后做比较啊,变量怎么能传出来啊。

解决方案 »

  1.   

    a.currentNum=?
    b.currentNum=?
    不就可以了吗?
      

  2.   

    不行啊,我要在第二个线程中进行比较,怎么引用第一个现成的成员变量啊,报错了
    non-static variable currentNum1 cannot be referenced from a static context
      

  3.   

    // 第二个数显示的时会慢一拍,但是我觉得不影响比较
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class Test extends Applet {
      public Dice[] dices =  new Dice[2];
      public Label result =  new Label("测试开始");   
      private Button  start = new Button("开始");
      public static int  count = 0;
      public static boolean isReady = false;
      
      public void init() {   
        for(int i = 0; i < dices.length; i++)
          dices[i] = new Dice(this);
        start.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e) {    
           for(int i = 0; i < dices.length; i++)
             dices[i].start();
         }
         }
        );    
        add(start);
        add(result);
      }  public  synchronized int getDiceNum()
      {
       isReady = !isReady; 
       int ret = (int)(10*Math.random());
       if (!isReady) {
       count ++;
    System.out.println("第" +Test.count+"次比较");
    System.out.println("两数为:");
    System.out.println(dices[0].diceNum+" "+ ret);
    if (dices[0].diceNum == ret){

    result.setText("两个相同");
    }else {
    result.setText("两个不同");
    }
    }
    return ret;
      }
      
      public static void main(String[] args) {
        Test applet = new Test();
        Frame aFrame = new Frame("Test");
        aFrame.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e){
              System.exit(0);
            }
          });
        aFrame.add(applet, BorderLayout.CENTER);
        aFrame.setSize(350, 100);
        applet.init();
        applet.start();
        aFrame.setVisible(true);
      }
      
      // 筛子类
    class Dice extends Thread {
      private boolean started = false;
      public TextField tf = new TextField(5);
      public int diceNum = 0;
      public Dice(Container g) {
        Panel p = new Panel();
        p.add(tf);
        g.add(p);
      }    
      public void start() {
        if(!started) {
          started = true;
          super.start();
        }
      }
      public void run() {
        while (true) {
          diceNum = getDiceNum();
          tf.setText(Integer.toString(diceNum));
          try {
            sleep(500);
          } catch (InterruptedException e){}
        }
      }  
    }
    }