当前位置:嗨网首页>书籍在线阅读

20-案例实现

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

案例实现

根据如下步骤来实现本案例。

1.创建一个 Contact 类:

public class Contact {

2.声明两个 String 类型的私有字段 namephone

private final String name;
private final String phone;

3.实现一个 Contact 类的构造方法来初始化字段:

public Contact(String name, String phone) {
  this.name=name;
  this.phone=phone;
}

4.分别实现 namephone 字段的方法:

public String getName() {
  return name;
}
public String getPhone() {
  return phone;
}

5.创建一个 Task 类并实现 Runnable 接口:

public class Task implements Runnable {

6.声明一个 ConcurrentSkipListMap<String, Contact> 的私有字段 map

private final ConcurrentSkipListMap<String, Contact> map;

7.声明一个 String 类型的私有字段 id ,以存储当前任务的ID值:

private final String id;

8.实现一个 Task 类的构造方法来初始化其字段:

public Task (ConcurrentSkipListMap<String, Contact> map,String id){
  this.id=id;
  this.map=map;
}

9.实现 run() 方法。用ID和自增数值来创建1000个 Contact 类的对象并用 put() 方法将其存储到 map 里面:

@Override
public void run() {
  for (int i=0; i<1000; i++) {
    Contact contact=new Contact(id, String.valueOf(i+1000));
    map.put(id+contact.getPhone(), contact);
  }
}

10.在 Main 类中实现一个 main() 方法:

public class Main {
  public static void main(String[] args) {

11.创建一个 ConcurrentSkipListMap<String, Contact> 类型的对象 map

ConcurrentSkipListMap<String, Contact> map = new
                                  ConcurrentSkipListMap<>();

12.创建一个长度为26的线程数组,并用它存储所有将要执行的 Task 对象:

Thread threads[]=new Thread[26];
int counter=0;

13.创建并启动26个 Task 对象,给它们分别赋予不同的字母作为对象ID:

for (char i='A'; i<='Z'; i++) {
  Task task=new Task(map, String.valueOf(i));
  threads[counter]=new Thread(task);
  threads[counter].start();
  counter++;
}

14.用 join() 方法来等待所有线程执行完成:

for (Thread thread : threads){
  try {
    threads[i].join();
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
}

15.用 firstEntry() 方法来获取 map 中的第一个对象,并把它打印到控制台中:

System.out.printf("Main: Size of the map: %d\n",map.size());
Map.Entry<String, Contact> element;
Contact contact;
element=map.firstEntry();
contact=element.getValue();
System.out.printf("Main: First Entry: %s: %s\n", contact.getName(),
                  contact.getPhone());

16.用 lastEntry() 方法来获取 map 中的最后一个对象,并把它打印到控制台中:

element=map.lastEntry();
contact=element.getValue();
System.out.printf("Main: Last Entry: %s: %s\n", contact.getName(),
                  contact.getPhone());

17.用 subMap() 方法来获取 map 的一个子集,并把它打印到控制台中:

  System.out.printf("Main: Submap from A1996 to B1002: \n");
  ConcurrentNavigableMap<String, Contact> submap=map
                                       .subMap("A1996","B1002");
  do {
    element=submap.pollFirstEntry();
    if (element!=null) {
      contact=element.getValue();
      System.out.printf("%s: %s\n", contact.getName(),
                        contact.getPhone());
      }
    } while (element!=null);
}