今天再次复习了线程方面的知识,所以写一篇博客,进行记录一下。
涉及知识点:1,多线程 2,多线程的同步。
设计类:1,Hero.java 2,TestThread.java
描述: 多线程演示: 同一时间有相同数量的线程,进行相加和减同一个角色的hp值:
Hero.java:
public class Hero {
private StringBuffer name; //人物姓名
private float hp; //生命值
private int damage; //伤害值
public Hero(StringBuffer name, float hp, int damage) {
this.name = name;
this.hp = hp;
this.damage = damage;
}
public StringBuffer getName() {
return name;
}
public float getHp() {
return hp;
}
public int getDamage() {
return damage;
}
/*使用synchronized 进行修饰,表示方法是线程安全*/
//加血
public synchronized void recovery() {
this.hp =this. hp + 1;
System.out.printf("recovery:当前hero:%s,hp值为%.0f%n", name, hp);
}
//攻击,减血
public synchronized void attack() {
this.hp = this.hp -1;
System.out.printf("attack:当前hero:%s,hp值为%.0f%n", name, hp);
}
}
TestThread.java:
/*
* 多线程演示:
* 同时有相同数量的线程,进行相加和减一个角色的hp值:
* 1,synchronize,线程同步使用方法:
* 方法1:可以使用 synchronize进行修饰方法,被称为线程安全
* 方法2:在run(){ synchronize(同步对象){ 方法 }};
* 2,StringBuffer 线程安全,StringBuilder 线程不安全
* 3,
* */
public class TestThread {
public static void main(String[] args) {
//多线程同步问题指的是多个线程同时修改一个数据的时候,导致的问题
//假设达摩有10000滴血,并且在基地里,同时又被对方多个英雄攻击
//用JAVA代码来表示,就是有多个线程在减少达摩的hp
//同时又有多个线程在恢复盖伦的hp
//n个线程增加达摩的hp
final Object O=new Object();
final Hero h1 = new Hero(new StringBuffer("达摩"), 100.0f, 150);
int n = 100;
Thread[] recoveryThread = new Thread[n];
Thread[] attackThread = new Thread[n];
//减血
for (int i = 0; i < n; i++) {
Thread t1 = new Thread() {
public void run() {
//同步
/* synchronized (this){
h1.attack();
}*/
//attack() 已经使用synchronized 进行修饰
h1.attack();
//暂停
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
attackThread[i] = t1;
}
//加血
for (int j = 0; j < n; j++) {
Thread t2 = new Thread() {
public void run() {
/* synchronized (this) {
h1.recovery();
}*/
//已经使用synchronized 修饰
h1.recovery();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t2.start();
recoveryThread[j] = t2;
}
//所有减血线程做完后,
for (Thread t1: attackThread){
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//所有加血线程做完后
for (Thread t2: recoveryThread){
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("当前hero:%s,hp值为%.0f%n",h1.getName(),h1.getHp());
}
}
/* 本人是个Java新手,如果有什么不对的地方,欢迎各位大佬们指正 */