我已经编写了一个应用程序,但是由于某种原因,它一直保持在100%的峰值。我在几个类上运行了一个概要文件r,并且有报告显示isReset()和isRunning()似乎被多次调用。你有什么不对的地方请通知我。谢谢
第1类是唯一使用isReset()代码的类,因此我希望这可以帮助您检测错误
1类
package SKA;
/*
* ver 0.32 June 2009
*
* Bug Fix Release:
*
* Fixed Array resize
* Fixed Red Black Tree delete method
* Fixed Red Black Tree save/read option
* Update help file
*
*/
/*
* Additions:
* ver 0.30 May 2009
*
* Added Red Black Tree structure
* Added Delete method for canvases
* Added Array structure
* Added ability to recolor nodes.
* Added Bubble Sort Algorithm
* Added Insertion Sort Algorithm
* Added Shell Sort Algorithm
* Added Selection Sort Algorithm
* Added Quick Sort Algorithm
* Added Red Black Tree Search Algorithm
* Added Black Height Check Algorithm
* Bug fix in canvas - could not delete canvas properly
*/
// Additions:
/* ver 0.25 August 2004
* Added recursion in SkaExecutionPanel by adding SkaFunction
* and using desktop internal panes.
*
* Added binary tree node annotation - text and drawn
* Added subtree highlight feature to VizBinaryTreeNode using SkaRectangle
* Improved node highlighting and selection scheme in VizBinaryTrees/VizDS
* Added Binary tree save and read methods
* Added visual subtree deletion (has bug)
*
* Added ability to set breaks from within algorithm
* Added tooltip messages to SkaProgram/SkaFunction to show variable values
* Added simple value input and output methods to SkaProgram/SkaFunction
* Added SkaTriangle.
* Added Font Adjustment and Color scheme options to show on overhead projectors
*
* Found bug in SkaGraph deleteVertex (with edges)
*/
/* ver 0.16 October 15, 2001
Added Graph save and read methods.
Save is an instance method, while read is a class method.
Added circular layout for graphs,
Added fit/adjust graph layout to plate size method.
Added label editing for Binary Trees and Graphs.
SkaLabels (glyphs) now truncate the string displayed to the width specified
in the constructor.
*/
/* ver 0.15 July 21, 2001
Fixed Reset function in Execution using exceptions so that Ska Algorithms
can be run repeatedly without quitting the entire Ska System.
This also allows trying the same program on different data structures.
Problems with reset so far:
1. Reset message to user can appear much later.
I think this is an I/O sequencing problem and it should go away if
a message status GUI area is used.
2. Bound variable names remain afterwards,
e.g. Graph bound to G will still show name as G after
algorithm is interrupted.
Fixed problem with multiple input requests in 0.14 - by adding another
wait call which waits on before asking for input.
Also introduced trial orderly layout of canvas and program windows ,
which fixes problem in 0.14
*/
/* ver 0.14 July 18, 2001
Added subclasses of SkaProgram, so that multiple programs
can run simultaneously.
Problem - when multiple programs start, their windows overlay each other
Problem - Send DS to algorithm can get confused, if an algorithm
requests input while another is waiting on input or if
two algorithms request input at the same time
*/
/* ver 0.13
Added BinaryTree - does not have node value display yet.
Added arrows on edges of directed graphs
*/
/* ver 0.12
Added VizElementListener - separated from VizElement
Element Input menu item only highlights when input for that DS is requested
DS Input has been cleaned up
*/
/* ver 0.11
can ask user to select individual elements, e.g. vertices
removed standard java cloning code which wasn't being used anyway
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
// TimerQueue
public class SkaTest {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int CANVAS_X = 100;
public static final int CANVAS_Y = 100;
public static final int CANVAS_FRAME_WIDTH = WIDTH+100;
public static final int CANVAS_FRAME_HEIGHT = HEIGHT + 100;
public static final int EXEC_WIDTH = 550;
public static final int EXEC_HEIGHT = 400;
static VizDSList dsList = new VizDSList();
static SkaCanvas canvas = new SkaCanvas(dsList);
static JFrame canvasFrame = new JFrame("Data Structure Canvas");
static JMenuBar menuBar = new JMenuBar();
static JMenu algorithmMenu = new JMenu("Algorithm");
static JMenu dsMenu = new JMenu("Create");
static JMenu helpMenu = new JMenu ("Help");
static JLabel status = new JLabel(" ");
static SkaProgram[] alg;
static JFrame execFrame[];
static SkaExecutionPanel execPanel[];
public static void setupFrames(int nAlgs) {
int i;
for (i=0; i < nAlgs; i++) {
// execFrame[i] = new JFrame("Execution Control Panel "+(i+1));
execFrame[i] = new JFrame();
execPanel[i] = new SkaExecutionPanel(execFrame[i]);
}
canvas.setMinimumSize(new Dimension(WIDTH, HEIGHT));
canvasFrame.setSize(CANVAS_FRAME_WIDTH, CANVAS_FRAME_WIDTH);
canvasFrame.getContentPane().setLayout(new BorderLayout(10,7));
// canvasFrame.getContentPane().setPreferredSize(new Dimension(WIDTH, HEIGHT));
canvasFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// canvas.setMinimumSize(new Dimension(WIDTH, HEIGHT));
for (i=0; i < nAlgs; i++) {
execFrame[i].setSize(EXEC_WIDTH, EXEC_HEIGHT);
// execFrame[i].getContentPane().setLayout(new BorderLayout(10,7));
execFrame[i].addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
execPanel[i].setBorder(new SoftBevelBorder(BevelBorder.RAISED));
// execFrame[i].setContentPane(execPanel[i]);
execFrame[i].getContentPane().add("Center", execPanel[i]);
// execFrame[i].setLocation(CANVAS_X +CANVAS_FRAME_WIDTH, CANVAS_Y + i*EXEC_HEIGHT);
execFrame[i].setLocation(CANVAS_X +CANVAS_FRAME_WIDTH + i*30, CANVAS_Y + i*50);
}
canvas.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
canvasFrame.getContentPane().add("Center", new JScrollPane(canvas) );
// canvasFrame.getContentPane().add("Center", new JScrollPane(canvas, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) );
canvasFrame.getContentPane().add("South", status);
canvasFrame.setLocation(CANVAS_X, CANVAS_Y);
JMenu fileMenu = new JMenu("File");
JMenuItem quitItem = new JMenuItem("Quit");
//TODO Add quit listener
quitItem.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent arg0) {
//System.exit(0);
int again = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit system", "Exiting", JOptionPane.YES_NO_OPTION);
if (again == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
}
);
fileMenu.add(quitItem);
menuBar.add(fileMenu);
menuBar.add(algorithmMenu);
// menuBar.add(dsMenu);
menuBar.add(helpMenu);
JMenuItem help = new JMenuItem ("Help Contents");
//help.setMnemonic(KeyEvent.VK_H);
//TODO Fix this method
help.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, ActionEvent.CTRL_MASK));
help.addActionListener(new ActionListener()
{
/*
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Alot of the functionality have not yet been included in this version\nCurrently working on the automation features now!", "SKA 0.2 Beta", JOptionPane.WARNING_MESSAGE);
}
*/
public void actionPerformed(ActionEvent arg0) {
try {
Runtime.getRuntime().exec("hh.exe C:/ska.chm");
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JMenuItem about = new JMenuItem ("About SKA");
about.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "SKA Version 0.1 Beta");
}
});
helpMenu.add(help);
helpMenu.add(about);
canvasFrame.setJMenuBar(menuBar);
}
/** The create menu item */
public static void createProgram(int i) {
JMenuItem algItem;
switch (i) {
case 0 :
alg[0] = new RedBlackValidate(canvas, execPanel[0]);
execFrame[0].setTitle("Validate Algorithm");
System.out.println("Validate Algorithm");
algItem = new JMenuItem("Validate Algorithm");
algorithmMenu.add(algItem);
break;
/* case 0 :
alg[0] = new BreadthFirstSearch(canvas, execPanel[0]);
execFrame[0].setTitle("BFS Graph Algorithm");
// System.out.println("BreadthFirstSearch");
algItem = new JMenuItem("BFS Graph Algorithm");
algorithmMenu.add(algItem);
break;
case 1:
alg[1] = new LevelOrderAlgorithm(canvas, execPanel[1]);
execFrame[1].setTitle("Level Order Tree Algorithm");
System.out.println("LevelOrderAlgorithm");
algItem = new JMenuItem("Level Order Tree Algorithm");
algorithmMenu.add(algItem);
break;
case 2:
alg[2] = new BinarySearchTreeAlgRecursive(canvas, execPanel[2]);
execFrame[2].setTitle("BinaryTreeSearchRec Algorithm");
System.out.println("BinaryTreeSearchRec Algorithm");
algItem = new JMenuItem("BinaryTreeSearchRec Algorithm");
algorithmMenu.add(algItem);
break;
case 3:
alg[3] = new BinarySearchTreeAlgIterative(canvas, execPanel[3]);
execFrame[3].setTitle("BinaryTreeSearchIter Algorithm");
System.out.println("BinaryTreeSearchIter Algorithm");
algItem = new JMenuItem("BinaryTreeSearchIter Algorithm");
algorithmMenu.add(algItem);
break;
case 4:
alg[4] = new RebBlackTreeSearch (canvas, execPanel[4]);
execFrame[4].setTitle("Red Black Search Algorithm");
System.out.println("Red Black Search Algorithm");
algItem = new JMenuItem("Red Black Search Algoithm Algorithm");
algorithmMenu.add(algItem);
break;
case 5:
alg[5] = new ArrayInsertionSortAlg (canvas, execPanel[5]);
execFrame[5].setTitle("Array Insertion Sort Algorithm");
System.out.println("Array Insertion Sort");
algItem = new JMenuItem("Array Insertion Sort Algorithm");
algorithmMenu.add(algItem);
break;
case 6:
alg[6] = new ArraySelectionSortAlg (canvas, execPanel[6]);
execFrame[6].setTitle("Array Selection Sort Algorithm");
System.out.println("Array SelectionSearch");
algItem = new JMenuItem("Array Selection Sort Algorithm");
algorithmMenu.add(algItem);
break; */
default:
break;
}
}
public static void main(String args[]) {
int i, nAlgs = 1; //nAlgs = 7;
alg = new SkaProgram[nAlgs];
execPanel = new SkaExecutionPanel[nAlgs];
execFrame = new JFrame[nAlgs];
// canvas.setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION);
setupFrames(nAlgs);
canvasFrame.setVisible(true);
for (i=0; i < alg.length; i++) {
createProgram(i);
execFrame[i].setVisible(true);
alg[i].start();
alg[i].displayAlgorithm();
}
while (true) {
for (i=0; i < alg.length; i++)
if (execPanel[i].isReset()) {
alg[i].terminate();
createProgram(i);
alg[i].start();
execPanel[i].unreset();
}
}
}
} // End class SkaTest
2级
package SKA;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Stack;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
@SuppressWarnings("serial")
public
class SkaExecutionPanel extends JDesktopPane {
public static final int EXEC_WIDTH = SkaTest.EXEC_WIDTH-100;
public static final int EXEC_HEIGHT = SkaTest.EXEC_HEIGHT-50;
boolean run = false, pause = true, step = false, reset = false;
JToolBar toolbar = new JToolBar();
JTextArea textOutputArea = new JTextArea();
SkaProgram prog;
Stack<SkaFunction> functionStack = new Stack<SkaFunction>();
SkaFunction currentFunction = null;
int level = 0, in = 30;
public void doCall(String[] subAlg, String subAlgName) {
doCall(subAlg, subAlgName, false); // make non-icon default
}
public void doCall(String[] subAlg, String subAlgName, boolean iconify) {
if (currentFunction != null)
functionStack.push(currentFunction);
currentFunction = new SkaFunction(this, subAlg, subAlgName, iconify);
add(currentFunction, new Integer(1));
currentFunction.setBounds(level*in,level*in,EXEC_WIDTH, EXEC_HEIGHT);
// currentFunction.setBounds(level*in,level*in,EXEC_WIDTH-(level+1)*in, EXEC_HEIGHT-(level+1)*in);
currentFunction.setVisible(true);
level++;
}
public void doReturn() {
if (currentFunction == null)
return;
if (currentFunction.makeIconWhenDone()) {
getDesktopManager().iconifyFrame(currentFunction);
// currentFunction.setIcon(true);
currentFunction.setIconifiable(true);
}
else
currentFunction.setVisible(false);
currentFunction = (SkaFunction) functionStack.pop();
level--;
}
public void displayAlgorithm(String[] a) {
doCall(a, "main");
}
public void displayAlgorithm(String[] a, String aname) {
doCall(a, aname);
}
public void setControlsEnabled(boolean b) {
toolbar.setEnabled(b);
}
class RunAction extends AbstractAction {
RunAction() {
super("run");
}
public void actionPerformed(ActionEvent e) {
run = true; pause = false; step = false;
}
}
class StepAction extends AbstractAction {
StepAction() {
super("step");
}
public void actionPerformed(ActionEvent e) {
run = false; pause = false; step = true;
}
}
class PauseAction extends AbstractAction {
PauseAction() {
super("pause");
}
public void actionPerformed(ActionEvent e) {
pause = true;
// System.out.print("breaks");
// for (int i=0; i<breaks.length; i++)
// System.out.print("[" +i+ "]=" + breaks[i].toString() + " ");
// System.out.println("");
}
}
class ResetAction extends AbstractAction {
ResetAction() {
super("reset");
putValue(Action.SHORT_DESCRIPTION, "stop program and reset state to begining");
}
public void actionPerformed(ActionEvent e) {
run = false; pause = true; step = false;
// should also restart SkaProgram
reset = true;
if (currentFunction != null) currentFunction.reset();
/*
JInternalFrame[] frames = getAllFrames();
for (int i = 0; i < frames.length; i++) {
// frames[i].dispose();
if (frames[i].isIcon())
frames[i].dispose();
}
*/
}
}
JComboBox speedControl;
String speedNames[] = { "slow", "normal", "fast", "very fast" };
int speeds[] = {4000, 2000, 1000, 500} ; // milliseconds
int speed = speeds[1];
private void initSpeedMenu() {
speedControl = new JComboBox(speedNames);
// speedControl.setMaximumRowCount(3);
speedControl.addItemListener(
new ItemListener() {
public void itemStateChanged( ItemEvent e) {
speed = speeds[speedControl.getSelectedIndex()];
}
}
);
speedControl.setSelectedIndex(1);
speedControl.setMaximumSize(speedControl.getPreferredSize());
speedControl.setToolTipText("execution speed");
}
SkaExecutionPanel(JFrame frame) {
initSpeedMenu();
toolbar.add(new RunAction());
toolbar.add(new StepAction());
toolbar.add(new ResetAction());
toolbar.add(new PauseAction());
toolbar.addSeparator();
toolbar.add(speedControl);
// frame.getContentPane().setLayout(new BorderLayout(10,7));
// makeTable();
frame.getContentPane().add("North", toolbar);
Font f = new Font("SansSerif", Font.BOLD, 14);
textOutputArea.setFont(f);
frame.getContentPane().add("South", new JScrollPane(textOutputArea));
// frame.getContentPane().add(this, BorderLayout.CENTER)
// frame.getContentPane().add("Center", toolbar, BorderLayout.NORTH);
// setSize(300,250);
// add toolbar, table, set layout, sizes
}
// public void setAlgorithm(SkaProgram p) {
// prog = p;
// sendAlgorithm(p.getPseudocode());
// }
public int getSpeed() { return speed;
}
public boolean isRunning() { return run;
}
public boolean isPaused() { return pause;
}
public boolean isStepping() { return step;
}
public boolean isReset() { return reset;
}
public void pause() { pause = true;
}
public void unreset() { reset = false;
}
public void aboutToWait() {
currentFunction.aboutToWait();
}
public void doneWait() {
currentFunction.doneWait();
}
public void showToolTipValue(String s) {
currentFunction.showToolTipValue(s);
}
public void showAlgLineBreak(int i) {
currentFunction.showAlgLineBreak(i);
}
public void showAlgLine(int i) {
currentFunction.showAlgLine(i);
}
public void displayText(String s) {
textOutputArea.append(s); // +"\n" add newline?
}
} // End class SkaExecutionPanel
问题似乎并不在于常用的方法,而是
您调用它们的频率,这似乎就是它们出现如此
频繁的原因。我会检查所有电话,看看是否有多余的电话,然后转到
第三大耗时的方法。之后,我将检查
算法是否特别密集。另外,检查所有方法调用,
并确保它们不会在不需要时运行。
我知道这并不能解决问题本身,而是从
给出的信息开始。
编辑:while循环是一个无限循环,导致for循环运行,其中
已检查数组中的每个项目以查看其是否已重置。您可以
将其替换为观察者模式,在该观察者模式下,重置对象时,它
会通知观察对象,该对象随后执行该组步骤。这样,
您就没有无限循环,并且减少了.isReset()的使用。
这是Class 1的主要方法。
Edit 2: Here’s the example of an implementation of the
observer pattern which is on
wikipedia.
有没有代码写的漂亮的大佬,看看这个代码怎么优化,一直写前端的,突然被叫去搞java,发现很多技术都不太相同,例如动态的key去调用之类,导致写出这样的恶心代码,自己都看不下去了 明明js可以写的这么短小优雅,java有没有办法做到这样子的呢
我认为代码(如下)已经优化(只需使用比相同逻辑的初始版本更少的变量) > 在优化过程中,我应该考虑哪些因素? 这是代码(也在jsfiddle上) 这是代码的解释。“处理”函数在数组中查找相同的值,对于每个相同的值,它通过将一个数字挂起到该值来更改值,“数字”表示它在数组中找到的值的计数。 例如arr=["x","x","y","z"]将返回["x(1)","x(2)","y","z"]"y"和"z
本文向大家介绍美化java代码,从合理注释开始,包括了美化java代码,从合理注释开始的使用技巧和注意事项,需要的朋友参考一下 请停止代码注释 “干净的代码应该像写好的散文一样” - Robert C. Martin 不良代码的通病就是有很多注释。这是凌乱的源代码最明显的迹象。 每个程序员的目标应该是编写干净和富有表现力的代码,以避免代码注释。每个变量,函数和类的目的应该隐含在其名称和结构中。 当
问题内容: 编写Java程序时,对CPU如何利用其缓存存储数据有影响吗?例如,如果我有一个经常访问的数组,那么它是否足够小以适合一个高速缓存行(在64位计算机上通常为128字节)是否有帮助?如果我将一个经常使用的对象保持在该限制之内,我可以期望它的成员使用的内存紧密并留在缓存中吗? 背景:我正在构建一个压缩的数字树,它受C语言中Judy数组的启发很大。虽然我主要追求其节点压缩技术,但Judy将CP
Donald Knuth "过早的优化是一切罪恶的根源" 本章处理用策略让Python代码跑得更快。 先决条件 line_profiler gprof2dot 来自dot实用程序 2.4.1 优化工作流 让它工作起来:用简单清晰的方式来写代码。 让它可靠的工作:写自动的测试案例,以便真正确保你的算法是正确的,并且如果你破坏它,测试会捕捉到。 通过剖析简单的使用案例找到瓶颈,并且加速这些瓶颈,寻找更
我想写一个模拟 DNF 装备增幅的程序,通过多次样本执行得到平均每件增幅 10 装备需要增幅多少次。装备 +4 之前不会失败,+4 之后会失败且失败后还会掉级,具体如下图所示: 公会秘药和普雷宠物会额外增加每次增幅的成功率 1% 和 4%,所以一共分了三种情况。 我最开始用 js 写了一版: 后来想到我刚学了 rust,不如练练手,而且 rust 很快,于是又写了一版: 然而实际上 rust 代码