![]() |
#2
疯狂的小a2018-04-30 17:25
![]() package com.xiaoa.test; import java.util.HashMap; import java.util.Map; /*2、已知飞毛腿代收点共有1000件快递,创建两条线程代表两个快递员(张三,李四)每件快递提成0.5元, 同时开启这两条线程进行送件,每次送件需要耗时5ms;在控制台输出两个快递员分别送了多少件快递以及赚了多少提成(10分) 例如: 李四送了392件快递,共赚196.0元 张三送了608件快递,共赚304.0元*/ public class ThreadDemo { public static void main(String[] args) { MyRunnable m = new MyRunnable(); // 创建线程对象 Thread t1 = new Thread(m); t1.setName("李四"); t1.start(); Thread t2 = new Thread(m); t2.setName("张三"); t2.start(); } } class MyRunnable implements Runnable { //private static final String Map = null; static int num = 1000; static double count1 = 0; static double count2 = 0; @Override public void run() { Map<String, Double> map = new HashMap<>(); while (true) { try { Thread.sleep(5); synchronized (this) { if (num > 0 && Thread.currentThread().getName().equals("李四")) { count1++; num--; map.put("李四", count1 * 0.5); } else if (num > 0) { count2++; num--; map.put("张三", count2 * 0.5); }else { break; } } } catch (InterruptedException e) { e.printStackTrace(); } } //Set<String> keySet = map.keySet();// 在这里为什么不可以遍历集合? for(String key:map.keySet()) { System.out.println(key+" : "+map.get(key)); } } } |
/*2、已知飞毛腿代收点共有1000件快递,创建两条线程代表两个快递员(张三,李四)每件快递提成0.5元,
同时开启这两条线程进行送件,每次送件需要耗时5ms;在控制台输出两个快递员分别送了多少件快递以及赚了多少提成(10分)
例如:
李四送了392件快递,共赚196.0元
张三送了608件快递,共赚304.0元*/
public class TreadDemo {
public static void main(String[] args) {
MyRunnable m = new MyRunnable();
//创建线程对象
Thread t1 = new Thread(m);
t1.setName("李四");
t1.start();
Thread t2 = new Thread(m);
t2.setName("张三");
t2.start();
}
}
class MyRunnable implements Runnable {
private static final String Map = null;
int num = 1000;
@Override
public void run() {
// TODO Auto-generated method stub
double count1 = 0;
double count2 = 0;
java.util.Map<String,Double> map = new HashMap<>();
while (true) {
try {
Thread.sleep(5);
synchronized (this) {
if (num > 0 && Thread.currentThread().getName().equals("李四")) {
count1++; num--;
map.put("李四",count1*0.5);
}else if(num > 0){
count2++; num--;
map.put("张三", count2*0.5);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Set<String> keySet = map.keySet();//在这里为什么不可以遍历集合?
}
}