这基本上是一个简单的生产者-消费者应用程序。代码示例如下:
public class MyMainClass extends Application {
// blocking queue that will be shared among my prcesses
BlockingQueue bq;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
// parameters I wont the Thread passes to the server socket
TextArea parameters = new TextArea("parameters-for-the-server");
// setting the Producer button
Button btnProducer = new Button();
btnProducer.setText("Start Producer");
btnProducer.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/* ReadSocket connects to a web sockets,
reads strings and saves them into a shared blocking queue: bq*/
ReadSocket rs = new ReadSocket(bq);
new Thread(rs).start();
}
// setting the Consumer button
Button btnConsumer = new Button();
btnConsumer.setText("Start Consumer");
btnConsumer.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/* ReadSocket connects to a web sockets,
reads strings and saves them into a shared blocking queue: bq*/
Consumer c = new Consumer(bq);
new Thread(c).start();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
我的教授说,如果我希望它们可用于其他对象,我应该在构造函数中传递值。
我ReadSocket应该看起来像这样:
public class ReadSocket{
BlockingQueue bq;
ReadSocket(bq){
this.bq = bq;
// more code
}
那么,这是否意味着我必须传递我的价值观,例如:
ReadSocket rs = new ReadSocket(bq, parameters.getText()); 即使ReadSocket不是直接使用它们而是基于parameters? 这样做正确吗?还有其他更好的方法吗?
蛊毒传说
相关分类