[英]java swing paint with multithreads
我一直在尝试制作一个迷宫,其中的两个矩形将根据某些规则移动。问题是我必须使用多线程和线程池。我从未尝试过多线程并且在Java中有点新。我编写了一些代码。它正在工作,但是当我想显示当前线程ID(以证明两个线程同时工作)时,我得到了四个不同的线程号。即我不确定它是多线程的。请您有个好主意,告诉我我必须做。谢谢。
class Action extends JPanel{
Robot robot1,robot2;
public static Random rndm=new Random();
public Action() throws InterruptedException{
ExecutorService pool=Executors.newFixedThreadPool(2);
robot1=new Robot(0,560); // starts random free position
robot2=new Robot(0,560);
pool.submit(robot1);
System.out.println("rbt1 olustu");
pool.submit(robot2);
System.out.println("rbt2 olustu");
pool.shutdown();
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
robot1.MyDraw(g);
System.out.println("robot1 drawing");
robot2.MyDraw(g);
System.out.println("robot2 drawing");
}
class Robot implements Runnable{
int x;
int y;
Robot(int xCor,int yCor){
this.x=xCor;
this.y=yCor;
new Thread(this).start();
}
public void MyDraw(Graphics g){
if(end==false){
Image img1 = Toolkit.getDefaultToolkit().getImage("cat.jpg");
g.drawImage(img1, x, y,null);}
else{
g.setColor(Color.white);
g.drawRect(x, y, 40,40);
}
}
public void run() {
if(Frame.control==true){
while(true){
if(end==false){
decision(x,y);
visitedCell[x/40][y/40]+=1;
try{
Thread.sleep(300);
repaint();
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
}
else{
Thread.currentThread().interrupt();
System.out.println("Thread dead");
Frame.button4.setEnabled(true);
}
}
(我没有在这里放长的Decision()方法,它只是计算新的x,y坐标)
使用ExecutorService
,无需执行直接与线程一起使用的任何操作。 该服务为您完成。 在构造函数中,您正在制作(并启动线程)执行run方法。 然后,将它们添加到池中时,执行程序服务将使用2个Runnable,并在池中的两个线程中运行它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.