JAVA期末考试

本文涵盖了Java编程的基础知识,包括Map、线程池和锁的使用。深入讲解了类的设计原则,如单一职责原则和依赖倒置原则。讨论了Java虚拟机加载类的机制和数据库操作。还涉及到多线程、图形用户界面设计、链表排序以及多态和类型转换的演示。
摘要由CSDN通过智能技术生成

map

import java.util.*;
public class teachermap{
    public static void main(String[] args){
        //Set text in a string
        String text = "Good morning.Having a good class.";
        //Creat a TreeMap to hold words as key and count as value
        TreeMap <String,Integer> map = new TreeMap<String,Integer> (); 
        String[] words = text.split("[ \n\t\r.,;:!?(){}]");
        for(int i=0;i<words.length;i++){
            String key = words[i].toLowerCase();
            if(words[i].length()>1){
                if(map.get(key)==null) map.put(key,1);
                else{
                    int value = map.get(key).intValue();
                    value++;
                    map.put(key,value);
                }
            }
        }
        //Get all entries into a set
        Set <Map.Entry<String,Integer>> entrySet = map.entrySet();

        //Get key and value from the each entry
        for(Map.Entry<String,Integer> entry:entrySet)
            System.out.println(entry.getValue()+"\t"+entry.getKey());
    }   
}

thread pool

import java.util.concurrent.*;
    public class ExecutorDemo {
    public static void main(String[] args) {
     // Create a fixed thread pool with maximum three threads执行器创建三个线程来并发执行三个
    ExecutorService executor = Executors.newFixedThreadPool(3);

    // Submit runnable tasks to the executor
    executor.execute(new PrintChar('a', 100));
    executor.execute(new PrintChar('b', 100));
    executor.execute(new PrintNum(100));

    // Shut down the executor
    executor.shutdown();
   }
} 

如果将第5行改成 ExecutorService executor = Executors.newFixedThreadPool(1);
这三个任务将顺次执行,因为在线程池中只有一个线程。
如果改成ExecutorService executor = Executors.newFixedThreadPool();
为每个等待的人物任务创建一个新的线程,所以,所有的任务都并发地执行。

thread using lock

import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AccountWithSyncUsingLock {
   
  private static Account account = new Account();
  public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();
    // Create and launch 100 threads
    for (int i = 0; i < 100; i++) {
      executor.execute(new AddAPennyTask());
    }   
    executor.shutdown();
    // Wait until all tasks are finished
    while (!executor.isTerminated()) {
    }   
    System.out.println("What is balance ? " + account.getBalance());
  }
  // A thread for adding a penny to the account
  public static class AddAPennyTask implements Runnable {
   
    public void run() {
      account.deposit(1);
    }   
  }
  // An inner class for account
  public static class Account {
   
    private static Lo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值