您的位置:首页 > 编程语言 > Java开发

JAVA编程思想第四版-多线程的练习答案之练习17

2013-11-03 20:59 393 查看
package exercise.exercise17;

/**
* 计算所有传感器收集的辐射总数
* @author Administrator
*/
public class RadiationCount {

static int count = 0;

public synchronized void increment(){
count++;
}

public static synchronized int geiRadiationCount(){
return count;
}

}

package exercise.exercise17;

import java.util.concurrent.TimeUnit;

public class Sensor implements Runnable {

private static boolean isDone = false;
// 每个传感器内部存储的辐射数
int radiationCount = 0;

RadiationCount rc = null;

int id = 0;

public Sensor(){
rc = new RadiationCount();
}
public Sensor(int id) {
this.id = id;
rc = new RadiationCount();
}

@Override
public void run() {
while (!isDone) {
// 每检测到一个辐射就为传感器内部辐射器加1,然后往总的辐射计数器加1
synchronized (this) {
addRadition();
addSensorCount();

System.out.println(this);
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

System.out.println("# Stop   " + id);
}

public static void Done(){
isDone = true;
}

// 每收集一个辐射,就往总的辐射数里增加1
private void addRadition() {
synchronized (rc) {
rc.increment();
}
}

private void addSensorCount() {
synchronized (this) {
radiationCount++;
}
}

@Override
public String toString() {
return "# Sensor " + id
+ " Sensor has collected " + radiationCount;
}

}


package exercise.exercise17;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MainThread {

public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();

// 随机生成传感器个数
int sensorCount = (int) (Math.random() * 10);

for (int i = 0; i < sensorCount; i++) {
exec.execute(new Sensor(i));
}

try {
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Sensor.Done();
exec.shutdown();

try {
Thread.sleep(200);
if (!exec.awaitTermination(200, TimeUnit.MICROSECONDS)) {
System.out.println("Some task were not terminated!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("Sum of radiation "
+ RadiationCount.geiRadiationCount());
}
}

}


结果:

***
# Sensor 0 Sensor has collected 197
# Sensor 2 Sensor has collected 197
# Sensor 1 Sensor has collected 197
# Sensor 0 Sensor has collected 198
# Sensor 2 Sensor has collected 198
# Sensor 1 Sensor has collected 198
# Sensor 2 Sensor has collected 199
# Sensor 0 Sensor has collected 199
# Sensor 1 Sensor has collected 199
# Sensor 0 Sensor has collected 200
# Stop   2
# Stop   1
# Stop   0
Sum of radiation 584
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: