And*_*Kor 2 java methods synchronized runnable
我正在使用Swing创建一个游戏.我制作start()并stop()同步,因为我被告知它更好.同步做什么以及使用它有什么好处?
我的代码:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
public class SpritePractice extends Canvas implements Runnable{
private JFrame frame;
private final static int WIDTH = 200, HEIGHT = 200;
private final static int SCALE = 2;
private final static Dimension dimens= new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
private BufferedImage image;
private Graphics g;
private long nanoSecond = 1000000000;
private double tick = nanoSecond/60;
private boolean running = false;
private int pixelsFromImage[];
private int pixel[][];
private static DateFormat dateFormat = new SimpleDateFormat("[" + "yyyy/MM/dd HH:mm:ss"
+"]");
private static DateFormat dateFormat2 = new SimpleDateFormat("[" + "HH:mm:ss" + "]");
public SpritePractice()
{
frame = new JFrame("Bomberman");
frame.setSize(dimens);
frame.setMinimumSize(dimens);
frame.setMaximumSize(dimens);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setVisible(true);
init();
}
public void init()
{
long startTime = System.nanoTime();
Calendar cal = Calendar.getInstance();
System.out.println("START: " + dateFormat.format(cal.getTime()));
start();
}
public void run()
{
long now = System.nanoTime();
long lastTick = System.nanoTime();
long lastSecond = System.nanoTime();
int frames = 0;
while(running)
{
now = System.nanoTime();
Calendar cal = Calendar.getInstance();
if(now-lastTick >= tick)
{
lastTick = now;
tick();
render();
frames++;
}
if(now-lastSecond >= nanoSecond)
{
lastSecond = now;
System.out.println(dateFormat2.format(cal.getTime()) + "FPS: " + frames);
frames = 0;
}
}
}
public void tick()
{
//updates values
}
public void render()
{
BufferStrategy bs = getBufferStrategy();
if(bs==null)
{
createBufferStrategy(2);
return;
}
Graphics g = bs.getDrawGraphics();
g.fillRect(0, 0, WIDTH*2, HEIGHT*2);
g.dispose();
bs.show();
//renders graphics
}
public synchronized void start()
{
running = true;
run();
}
public synchronized void stop()
{
running = false;
}
public static void main(String[] args)
{
new SpritePractice();
}
Run Code Online (Sandbox Code Playgroud)
}