线程的模型
线程的五种状态
1、新建状态
2、就绪状态
3、运行状态
4、阻塞状态
5、死亡状态
最常见的两种
1、继承Thread类
使用情况:Java中只支持单继承,但一个类只要求实现单一的
线程功能是可以继承Thread类,当然也可以实现Runnable接口。
2、实现Runnable接口
使用情况:当一个类已经继承了某个了,但又要实现线程功能
一般通过实现Runnable接口实现。
多线程
一般的Java程序就有两个线程:其一是主线程,其二是垃圾回收
中的线程;多线程是定义在这两个之外的线程。
具体定义:是指从软件或者硬件上实现多个线程并发执行的技术
多线程的实例:每个小球对象对应一个线程,小球可以随机的产生。
public class GameFrame extends JFrame{
List<BallGame> list=new ArrayList<BallGame>();
double degree=Math.PI/6;
public void showFrame(){
setTitle("弹球游戏");
setSize(600, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
Random rand = new Random();
int count = 2;
for(int i =1;i<=count;i++){
BallGame ball = new BallGame(rand.nextInt(600),
rand.nextInt(600),
30,30,35,
new Color(rand.nextInt(255),
rand.nextInt(255)
,rand.nextInt(255)),degree);
list.add(ball);
}
new Thread() {
public void run() {
while(true){
for(BallGame ball :list){
int x=ball.getX();
int y=ball.getY();
x += ball.getM();
y += ball.getN();
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(x>=550){
ball.setM(-30);
}
if(x<0){
ball.setM(35);
}
if(y>=550){
ball.setN(-30);
}
if(y<0){
ball.setN(35);
}
ball.setX(x);
ball.setY(y);
repaint();
}
}
}
}.start();
}
public void paint(Graphics g){
super.paint(g);
for(int i=0;i<list.size();i++){
list.get(i).drawBall(g);
//碰撞检测
boolean impact =list.get(0).getRect().intersects(list.get(1).getRect());
if(impact){
list.get(i).setM(-20);
System.out.println("++++++++++++"+i);
}
}
}
}
线程锁是一种实现对多线程运行控制的方法;
在没有对多线程进行控制前,多线程的运行是随机的,
一般控制多线程的运行方法有:
1、同步块(线程锁)
2、自定义的控制器:通过控制while循环的条件的发生时机,来控制各个线程的运行顺序
同步块实例:简单的购票模拟
定义票类,用synchronized来锁定票的数量
package com.cast.many;
public class Ticket {
//票的数量
private int total;
public Ticket(int total){
this.total=total;
}
//得到票
public synchronized int getTicket(int number){
if(total>0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
total = total- number;
return total;
}else{
return 0;
}
}
}
如何去获得票;用synchronized锁定票
package com.cast.many;
public class GainThread extends Thread{
private String name;
private Ticket ticket;
private int number;
public GainThread(int number,Ticket ticket,String name){
this.number = number;
this.ticket=ticket;
this.name =name;
}
public void run(){
synchronized (ticket) {
int num = ticket.getTicket(number);
if(num>=0){
System.out.println(name+"您的取票数量为:"+number);
}else{
System.out.println(name +"票已售完,祝您下次好运!!!");
}
}
}
}
测试类
package com.cast.many;
public class Test {
public static void main(String[] args) {
Ticket ticket = new Ticket(20);
GainThread gain = new GainThread(2,ticket,"a");
GainThread buy = new GainThread(20, ticket, "b");
gain.start();
buy.start();
}
}