Java Swing中While循环的并发性
我一直在阅读Swing中的Java并发性,但找不到适合我的情况的答案 目标:让我的swing应用程序在while循环运行的同时运行,直到程序/应用程序退出 问题:程序冻结(正如我事先预料的那样),无法使用 尝试解决方案:我尝试在另一个线程上启动while循环,启动了它,但仍然没有任何结果 代码:Java Swing中While循环的并发性,java,swing,concurrency,swingworker,event-dispatch-thread,Java,Swing,Concurrency,Swingworker,Event Dispatch Thread,我一直在阅读Swing中的Java并发性,但找不到适合我的情况的答案 目标:让我的swing应用程序在while循环运行的同时运行,直到程序/应用程序退出 问题:程序冻结(正如我事先预料的那样),无法使用 尝试解决方案:我尝试在另一个线程上启动while循环,启动了它,但仍然没有任何结果 代码: 更新:通过使用SwingWorker类在后台执行while循环,我几乎可以完成我需要做的事情。 代码: 包装桩; 导入java.io.IOException; 导入java.util.concurr
更新:通过使用SwingWorker类在后台执行while循环,我几乎可以完成我需要做的事情。
代码:
包装桩;
导入java.io.IOException;
导入java.util.concurrent.AtomicBoolean;
导入javax.swing.SwingUtilities;
导入javax.swing.SwingWorker;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
公共类StakeMeServer{
私有静态AtomicBoolean online=新的AtomicBoolean(false);
public static GameServerLoop gsl=新GameServerLoop();
公共静态void main(字符串[]args)引发IOException{
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不受支持的ookandfeelException e){
e、 printStackTrace();
}
新的控制台界面(“服务器”,800400,假);
}
});
//在程序生命周期内,应始终运行此命令
gsl.execute();
}
静态类GameServerLoop扩展SwingWorker{
@凌驾
受保护的Void doInBackground(){
系统输出打印项次(“1”);
while(true){
while(online.get()){
系统输出打印项次(“2”);
}
}
}
}
}
一切正常,都有问题。使用
System.out.println()
方法以处理速度运行(while loop)会使程序有些不响应。单击停止按钮将起作用。。最终。似乎由于大量的System.out.println()
调用,所有内容都已备份。所以你不完整的例子留下了很多未回答的问题,基本上是这样的
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StakeMeServer {
private ServerSocket socket;
private Thread t;
private AtomicBoolean online = new AtomicBoolean(false);
public static void main(String[] args) throws IOException {
new StakeMeServer();
}
public StakeMeServer() {
SwingUtilities.invokeLater(new Runnable() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
open();
Thread t = new Thread(() -> {
System.out.println("1");
while (online.get()) {
System.out.println("2");
}
});
t.setDaemon(true);
t.setName("GameServer");
t.start();
}
public void open() {
System.out.println("Starting Server...");
online.set(true);
System.out.println("Server Online");
}
public void close() {
System.out.println("Stopping Server...");
online.set(false);
System.out.println("Server Offline");
}
public class TestPane extends JPanel {
private int x = 0;
private int delta = 4;
private JLabel state;
public TestPane() {
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x += delta;
if (x + 10 > getWidth()) {
x = getWidth() - 10;
delta *= -1;
} else if (x < 0) {
x = 0;
delta *= -1;
}
state.setText(Boolean.toString(online.get()));
repaint();
}
});
timer.start();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
state = new JLabel(Boolean.toString(online.get()));
add(state, gbc);
JButton btn = new JButton("Stop");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
close();
}
});
add(btn, gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval(x, (getHeight() / 2) - 5, 10, 10);
g2d.dispose();
}
}
}
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.GridBagConstraints;
导入java.awt.GridBagLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.IOException;
导入java.net.ServerSocket;
导入java.util.concurrent.AtomicBoolean;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.SwingUtilities;
导入javax.swing.Timer;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
公共类StakeMeServer{
专用服务器插座;
私有线程t;
private AtomicBoolean online=新的AtomicBoolean(false);
公共静态void main(字符串[]args)引发IOException{
新的StateMeserver();
}
公共StakeMeServer(){
SwingUtilities.invokeLater(新的Runnable(){
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
例如printStackTrace();
}
JFrame=新JFrame(“测试”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(newtestpane());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
});
open();
线程t=新线程(()->{
系统输出打印项次(“1”);
while(online.get()){
系统输出打印项次(“2”);
}
});
t、 setDaemon(true);
t、 设置名称(“游戏服务器”);
t、 start();
}
公开作废{
System.out.println(“启动服务器…”);
online.set(true);
System.out.println(“服务器在线”);
}
公众假期结束(){
System.out.println(“停止服务器…”);
online.set(false);
System.out.println(“服务器脱机”);
}
公共类TestPane扩展了JPanel{
私有整数x=0;
私有整数增量=4;
私有国家;
公共测试窗格(){
计时器计时器=新计时器(40,新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
x+=δ;
如果(x+10>getWidth()){
x=getWidth()-10;
delta*=-1;
}else如果(x<0){
x=0;
delta*=-1;
}
state.setText(Boolean.toString(online.get());
重新油漆();
}
});
timer.start();
setLayout(新的GridBagLayout());
GridBagConstraints gbc=新的GridBagConstraints();
gbc.gridwidth=GridBagConstraints.rements;
state=newjlabel(Boolean.toString(online.get());
添加(州,gbc);
JButton btn=新JButton(“停止”);
btn.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
btn.setEnabled(false);
close();
}
});
添加(bt)
package stakeme;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StakeMeServer {
private static AtomicBoolean online = new AtomicBoolean(false);
public static GameServerLoop gsl = new GameServerLoop();
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
new ConsoleGUI("Server", 800, 400, false);
}
});
//this should always be running during the life of the program
gsl.execute();
}
static class GameServerLoop extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() {
System.out.println("1");
while (true) {
while (online.get()) {
System.out.println("2");
}
}
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class StakeMeServer {
private ServerSocket socket;
private Thread t;
private AtomicBoolean online = new AtomicBoolean(false);
public static void main(String[] args) throws IOException {
new StakeMeServer();
}
public StakeMeServer() {
SwingUtilities.invokeLater(new Runnable() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
open();
Thread t = new Thread(() -> {
System.out.println("1");
while (online.get()) {
System.out.println("2");
}
});
t.setDaemon(true);
t.setName("GameServer");
t.start();
}
public void open() {
System.out.println("Starting Server...");
online.set(true);
System.out.println("Server Online");
}
public void close() {
System.out.println("Stopping Server...");
online.set(false);
System.out.println("Server Offline");
}
public class TestPane extends JPanel {
private int x = 0;
private int delta = 4;
private JLabel state;
public TestPane() {
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
x += delta;
if (x + 10 > getWidth()) {
x = getWidth() - 10;
delta *= -1;
} else if (x < 0) {
x = 0;
delta *= -1;
}
state.setText(Boolean.toString(online.get()));
repaint();
}
});
timer.start();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
state = new JLabel(Boolean.toString(online.get()));
add(state, gbc);
JButton btn = new JButton("Stop");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btn.setEnabled(false);
close();
}
});
add(btn, gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval(x, (getHeight() / 2) - 5, 10, 10);
g2d.dispose();
}
}
}