带有多线程的java swing paint
我一直在尝试制作一个迷宫,两个矩形将根据一些规则移动。问题是我必须使用多线程和线程池。我从未尝试过多线程,在Java中有点新。我编写了一些代码。我测试了它。它正在工作,但当我想显示当前线程id(以证明两个线程同时工作)时,我得到了四个不同的线程编号。也就是说,我不确定它是多线程。如果你有想法,请告诉我我必须做什么。谢谢带有多线程的java swing paint,java,multithreading,swing,Java,Multithreading,Swing,我一直在尝试制作一个迷宫,两个矩形将根据一些规则移动。问题是我必须使用多线程和线程池。我从未尝试过多线程,在Java中有点新。我编写了一些代码。我测试了它。它正在工作,但当我想显示当前线程id(以证明两个线程同时工作)时,我得到了四个不同的线程编号。也就是说,我不确定它是多线程。如果你有想法,请告诉我我必须做什么。谢谢 class Action extends JPanel{ Robot robot1,robot2; public static Random rndm=new Random()
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坐标)当您使用
执行器服务时,您不必做任何直接与线程一起工作的事情。这项服务是为你做的。在构造函数中,您正在创建(并启动一个线程)以执行run方法。然后,当您将它们添加到池中时,executor服务将获取2个Runnable并在池中的两个线程中运行它们。没关系,谢谢你。但我也想在MyDraw()方法中向每个线程加载不同的图像。例如robot1 cat.jpg、robot2 dog.jpg。我尝试了不同的事情,但它们不起作用。现在我可以加载两个线程相同的图片:(@user1073777:将要加载的图像作为参数传递给构造函数。您的可运行
实际上只关心绘制,而不是绘制的内容。@user1073777:附带说明,Swing不是为线程安全而设计的。