java 线程 获取消息,使用Java线程获取和发送消息

I want to make a thread, which runs, computes something with the data i give it, and returns a few values, or an object. The thread is a part of a Swing GUI.

My question: How can I make a method that runs when I make the thread, and returns an object (or whatever I want it to return)?

My code:

private void nextTurn () {

// do something

if (turn == white) {

try {

Engine e = new Engine(); // Engine is implemented by runnable

e.start();

Move m = e.getBestMove (board);

// thread should work, next code should be excecuted immediately

}

catch (Exception e) {}

}

// end of Main class

}

This is the first time I am working with Threads, and I know you should avoid them if possible, but I need it this time for my GUI.

The info on the Oracle site on Threads did not help me out. I am able to make a program with multiple Threads that runs indefinately, but I can't make it work with functions.

解决方案

Since this is with a Swing GUI, consider using a SwingWorker object which creates a background thread (all the code run in the doInBackground method), and then can return a final result and/or interim results. Information on how to use this is well documented in the tutorials here:

SwingWorkers have property change support and thus will allow listeners to observe its state (as a SwingWorker.StateValue) via a PropertyChangeListener. This is one way your program can determine that the thread has completed its processing, get the returned result and go from there.

On an unrelated note, this isn't in your production code is it?:

catch (Exception e) {}

If so, you will likely want to fix this as ignored exceptions can bite you in the tail big time.

e.g.,

if (turn == white) {

try {

final SwingWorker mySwingWorker = new SwingWorker() {

@Override

protected Move doInBackground() throws Exception {

Engine e = new Engine(); // Engine is implemented by runnable

e.start();

Move m = e.getBestMove(board);

return m;

}

};

mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {

public void propertyChange(PropertyChangeEvent evt) {

if (StateValue.DONE == mySwingWorker.getState()) {

try {

Move m = mySwingWorker.get();

// TODO: insert code to run on the EDT after move determined

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

}

}

});

mySwingWorker.execute();

} catch (Exception e) {

e.printStackTrace();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值