不行啊,我要在第二个线程中进行比较,怎么引用第一个现成的成员变量啊,报错了 non-static variable currentNum1 cannot be referenced from a static context
// 第二个数显示的时会慢一拍,但是我觉得不影响比较 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){
b.currentNum=?
不就可以了吗?
non-static variable currentNum1 cannot be referenced from a static context
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){}
}
}
}
}