多线程控制多小球问题

xiaoxianu 2016-11-09 07:48:47
import java.awt.*;

import javax.swing.*;

class MyWindow extends JFrame implements Runnable
{
int i = 0, x = 10, y;
Thread a;
Thread b;

MyWindow()
{
this.setBackground(Color.white);
this.setBounds(200, 200, 200, 200);
this.setVisible(true);
a.start();
b.start();
}
public void paint(Graphics g)
{
Color c = g.getColor();
g.setColor(Color.BLUE);
g.fillRect(x, y, 20, 15);
g.setColor(c);
}
public void run()
{
a = new Thread(this);
b = new Thread(this);
while(true)
{
synchronized(this)
{
if(Thread.currentThread() == a)
{
x = x + 2;
y = 35;
Thread a = new Thread(this);
}
else if(Thread.currentThread() == b)
{
x = x + 2;
y = 60;
Thread b = new Thread(this);
}
}
}
}
}

class B
{
public static void main(String[] args)
{
MyWindow w = new MyWindow();
}
}
...全文
151 2 打赏 收藏 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ipqtjmqj 2016-11-09
  • 打赏
  • 举报
回复
线程里面要调用repaint, 重写paint方法要先调用super.paint, 两个thread new 一次就够了 线程里面sleep一下,否则速度太快看不到了

import java.awt.*;

import javax.swing.*;

class MyWindow extends JFrame implements Runnable
{
	int x = 10, y;
	Thread a = new Thread(this);
	Thread b = new Thread(this);

	MyWindow()
	{	
		this.setBackground(Color.white);
		this.setBounds(200, 200, 200, 200);
		this.setVisible(true);
		a.start();
		b.start();
	}
	public void paint(Graphics g)
	{
		super.paint(g);
		Color c = g.getColor();
		g.setColor(Color.BLUE);
		g.fillRect(x, y, 20, 15);
		g.setColor(c);
	}
	public void run()
	{
		while(true)		
		{synchronized(this){
			if(Thread.currentThread() == a)
			{
				x = x + 2;
				y = 35;
			}
			else if(Thread.currentThread() == b)
			{
				x = x + 2;
				y = 60;
			}
			repaint(1, 0, 0, 200, 200);
				
			try
			{
			    Thread.sleep(500);
			}
			catch (InterruptedException e)
			{
			    e.printStackTrace();
			}
			
		}}
	}
}

class B
{
	public static void main(String[] args)
	{
		MyWindow w = new MyWindow();
	}
} 
ipqtjmqj 2016-11-09
  • 打赏
  • 举报
回复
Thread a; Thread b;的初始化应该在构造函数,没有new直接调用当然报NullPointerException

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧