java线程和进程(运用多线程的小球碰撞游戏)

2024-05-12 23:32

本文主要是介绍java线程和进程(运用多线程的小球碰撞游戏),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

进程是什么?在我的理解中,进程就是程序执行的一个实例,比如说你运行了十个ie,那么就有10个独立的ie进程,另外,如果你打开windows系统的任务管理器,在进程标签下显示的就是当前系统运行的进程。每个进程都有自己的一块内存空间,和一系列的系统资源,其数据和状态完全独立。

线程是什么?线程是进程中的一个实体,自己不占用系统资源,但其与所属进程的其他线程共享进程所拥有的全部资源。线程本身的数据只有cpu的寄存器数据。

 

java中线程的实现:

1.定义一个线程类,继承Threads类并重写run方法;

2.定义一个类,实现Runnable接口,重写目标对象从Runnable得到的run()方法。

线程的状态:

1.创建状态:Thread thread = new Thread();注意:此时系统并不为它分配资源,它只是一个空的线程对象;

2.运行状态:thread.start();

3.不可运行状态:由于某种原因导致线程无法继续运行,调用了wait、sleep、suspend方法或发生了线程阻塞,出现等待状态;

4.死亡状态:1.线程执行完毕,自然销毁;2.线程调用了stop方法

 

以下是运用线程编写的小球碰撞程序,其中小球类继承了Thread类。

主界面类:

 

package cn.lzj0801;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* 小球主界面,继承了JFrame类
* 
* @author lzj
* 
*/
public class BallFrame extends JFrame {
public static void main(String[] args) {
BallFrame df = new BallFrame();// 創建DrawFrame對象
df.iniUI();// 調用iniUI方法
}
public void iniUI() {
this.setTitle("线程入门");
this.setSize(700, 700);
this.setResizable(false);// 设置窗体大小不可改变
this.setDefaultCloseOperation(3);
this.getContentPane().setBackground(Color.WHITE);
this.setLocationRelativeTo(null);// 设置居中
//		 this.setUndecorated(true);
// 设置流式布局
java.awt.FlowLayout fl = new java.awt.FlowLayout();
this.setLayout(fl);
this.setVisible(true);
JButton jbuAdd = new JButton("创建");
JButton jbuStart = new JButton("启动");
JButton jbuStop = new JButton("暂停");
// 把按钮添加到窗体上
this.add(jbuAdd);
this.add(jbuStop);
this.add(jbuStart);
BallListener bl = new BallListener(this);// 创建小球监听器对象
// 添加按钮监听器
jbuAdd.addActionListener(bl);
jbuStart.addActionListener(bl);
jbuStop.addActionListener(bl);
jbuAdd.setFocusable(false);
jbuStart.setFocusable(false);
jbuStop.setFocusable(false);
this.addMouseListener(bl);
}
}

 

  监听器类:

package cn.lzj0801;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* 这是一个监听器类,实现了ActionListener接口
* 
* @author lzj
* 
*/
public class BallListener implements java.awt.event.ActionListener,
MouseListener {
java.util.Random rand = new java.util.Random();
BallFrame bf;
private int x, y;
MyArrayList<BallThread> al = new MyArrayList<BallThread>();
// 重写构造方法
public BallListener(BallFrame bf) {
this.bf = bf;
}
// 重写监听器的事件处理方法
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
if (str.equals("创建")) {
System.out.println("=======================" + str);
BallThread ball = new BallThread(rand.nextInt(700),
rand.nextInt(700), 20, 8, 8, bf, al);
ball.start();
al.add(ball);
} else if (str.equals("启动")) {
for (int i = 0; i < al.size(); i++) {
BallThread ball = al.get(i);
ball.stateFlag = false;
}
} else if (str.equals("暂停")) {
for (int i = 0; i < al.size(); i++) {
BallThread ball = al.get(i);
ball.stateFlag = true;
}
} else if (str.equals("删除")) {
BallThread ball = al.get(al.size()-1);
al.delete(al.size()-1);
ball.flag = true;
}
}
@Override
public void mouseClicked(MouseEvent e) {
// x = e.getX();
// y = e.getY();
// for (int i = 0; i < al.size(); i++) {
// int ox = al.get(i).getX() + al.get(i).getSize() / 2;
// int oy = al.get(i).getY() + al.get(i).getSize() / 2;
// System.out.println("delete");
// if (Math.sqrt(Math.abs(x-ox) * Math.abs(x - ox) + Math.abs(y - oy) *
// Math.abs(y - oy)) <= al.get(
// i).getSize() / 2) {
// al.delete(i);
// al.get(i).flag = true;
// }
// }
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}

 

小球类:

package cn.lzj0801;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class BallThread extends Thread {
private int x, y, size, movex, movey;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
private BallFrame bf;
private Graphics g;
boolean stateFlag = false;// 声明布尔类型的变量表示状态
boolean flag = false;
java.util.Random rand = new java.util.Random();
private Image img = new javax.swing.ImageIcon("images\\doge.gif")
.getImage();
MyArrayList<BallThread> al;
BallThread ball;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
private int a = rand.nextInt(255);
private int b = rand.nextInt(255);
private int c = rand.nextInt(255);
// 重写构造方法
public BallThread(int x, int y, int size, int movex, int movey,
BallFrame bf, MyArrayList al) {
this.x = x;
this.y = y;
this.size = size;
this.movex = movex;
this.movey = movey;
this.bf = bf;
g = this.bf.getGraphics();
this.al = al;
}
// 重写run方法
public void run() {
while (!flag) {
System.out.println();
if (stateFlag) {// 若stateFlag为true,执行continue,进行空循环,不执行下面的语句;否则,执行下面的语句
continue;
}
g.setColor(Color.WHITE);
g.fillOval(x, y, size, size);
// g.fillRect(x, y, size, size);
x += movex;
y += movey;
g.setColor(new Color(a, b, c));
g.fillOval(x, y, size, size);
// g.drawImage(img, x, y, size, size, null);
if (x > (700 - size) && movex > 0) {
movex = -movex;
}
if (y > (700 - size) && movey > 0) {
movey = -movey;
}
if (x < 2 && movex < 0) {
movex = -movex;
}
if (y < 25 && movey < 0) {
movey = -movey;
}
// 碰撞处理,比较圆心之间距离,遍历数组队列,找出当前球与其他球的圆心距离
for (int i = 0; i < al.size(); i++) {
ball = al.get(i);
if (this == ball) {
continue;
}
int xx = Math.abs(this.x - ball.x);
int yy = Math.abs(this.y - ball.y);
int xy = (int) Math.sqrt(xx * xx + yy * yy);
int tempx = 0;
int tempy = 0;
//boolean changeFlag =true;
if (xy <= (this.size / 2 + ball.size / 2 )) {
tempx = this.movex;
tempy = this.movey;
this.movex = ball.movex;
this.movey = ball.movey;
ball.movex = tempx;
ball.movey = tempy;
//					changeFlag = false;
}
}
try {
Thread.sleep(60);// 休眠0.01秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

 

数组队列类:

package cn.lzj0801;
/**
* 纯粹的数组队列,实行增删改查等功能,一个第三方的类
* 
* @author lzj
* 
*/
public class MyArrayList<E> {
private Object[] array;// 声明对象数组
private int size = 0;// 声明size属性,设置初值为0
/**
* 构造方法
*/
public MyArrayList() {
array = new Object[0];// 初始化
}
public MyArrayList(int size) {
array = new Object[size];// 初始化
}
/**
* 向数组队列中添加元素的方法
* 
* @param elements要添加的元素
*/
public void add(E element) {
// 创建一个新的数组,长度为size+1
Object[] newArray = new Object[size + 1];
for (int i = 0; i < size; i++) {
newArray[i] = array[i];// 赋值
}
newArray[size] = element;// 添加元素至数组最后的位置
size++;// size加1
array = newArray;// 把newArray的地址给array
}
/**
* 根据索引删除对应的元素(删除区别于移除,删除需要释放空间)
* 
* @param index要删除的元素的索引
* @return
*/
public E delete(int index) {
if (index < 0 || index >= size)// 防止所给下标为负值或超出size
return null;
Object temp;// Object类型变量
temp = array[index];// 将被删除的元素赋予临时变量temp
Object[] newArray = new Object[size - 1];// 创建Object类数组,数组长度减1
// 小于索引时,照搬过去
for (int i = 0; i < index; i++) {
newArray[i] = array[i];// 把值移到新数组中
}
// 大于索引时
for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];// 移位填补空位
newArray[i] = array[i];// 把值移到新数组中
}
array = newArray;// 把newArray的地址给array
size--;
return (E) temp;// 返回被删除的元素
}
/**
* 根据索引插入对应的元素
* 
* @param index要插入的位置的索引
* @return
*/
public E ins(int index, E element) {
Object[] newArray = new Object[size + 1];// 创建Object类数组,数组长度减1
// 小于索引时,照搬过去
for (int i = 0; i < index; i++) {
newArray[i] = array[i];// 把值移到新数组中
}
newArray[index] = element;
// 大于索引时
for (int i = index; i < size; i++) {
newArray[i + 1] = array[i];// 把值移到新数组中
}
array = newArray;// 把newArray的地址给array
size++;
return element;// 返回被插入的元素
}
// 得到数组队列的长度的方法
public int size() {
return size;
}
// 根据索引和传人的元素设定相应的元素
public void set(int index, E obj) {
array[index] = obj;
}
// 根据索引得到相应的元素
public E get(int index) {
if (index < 0 || index >= size)// 防止所给下标为负值或超出size
return null;
return (E) array[index];
}
public E find(E obj) {
for (int i = 0; i < size; i++) {
if (array[i].equals(obj))
return (E) array[i];
}
return null;
}
// 修改元素,根据元素和下标
public void modify(E element, int index) {
array[index] = element;
}
}

 

这篇关于java线程和进程(运用多线程的小球碰撞游戏)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/984046

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏