今天再次複習了線程方面的知識,是以寫一篇部落格,進行記錄一下。
涉及知識點: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());
}
}