(一)进程与线程的关系:
系统每启动一个任务就会开启一个新的进程,一个任务的一个或者多个线程只能在该任务进程的作用域内运行,各各进程间互不干扰,没有共用的内存空间。
(二)JAVA创建进程的方法:
(1):继承Thread类覆盖它的run()方法。
public void run() {
while(true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 0;
System.out.println(i);
}
}
while(ture)设置了一个死循环,让系统无限打印1。在运行线程的时候,应调用该类的start()方法, 这样run()方法将被作为一个线程来执行,且可以启动多个。若调用run()方法,则像运行普通方法一样, 无法启动多个,且程序会变卡。
(2):实现Runnable接口实现它的run()方法。
因此,一个类如果已经继承了其他类只能通过实现Runnable接口来创建进程。
(三)基于线程的旅行钓鱼游戏:
线程休眠时间以毫秒为单位,最小为1,可以根据休息时间粗略估计程序执行的进度与现实时间
关系。
public void time() {
Abs++;
if(Abs%200 == 0) {
num++;
if(num == 5) {
num = 0;
}
}
if(Abs>= 8000) {
Abs = 0;
}
}
这是一个简易的计时器,可以在粗略让num在0~4之间循环,通过Thread休眠时间与Abs求余条件 的变换让num每次变动的间隔为1秒,来提取下面素材的分割。
public void drawFishA(Graphics g) {
time();
ImgWeight =image.getWidth(fishinpanel) / 5;
ImgHeight = image.getHeight(fishinpanel);
g.drawImage(image, this.X, this.Y, this.X + ImgWeight, this.Y + ImgHeight,
num * ImgWeight, 0, (num + 1) * ImgWeight, ImgHeight, null);
}
public void drawFishB(Graphics g) {
time();
ImgWeight =image.getWidth(fishinpanel) / 5;
ImgHeight = image.getHeight(fishinpanel);
g.drawImage(image, this.X, this.Y + ImgHeight, this.X + ImgWeight, this.Y,
(num + 1) * ImgWeight, ImgHeight, num * ImgWeight, 0, null);
}
A,B为画头朝向两种不同方向的鱼的方法。