21xrx.com
2024-12-22 19:54:30 Sunday
登录
文章检索 我的文章 写文章
题目及解析
2023-06-14 20:42:06 深夜i     --     --
Java 面试 字符串反转 单例模式 排序算法 正则表达式 线程池

Java是目前最流行的编程语言之一,无论是在IT行业还是其他行业,都有着广泛的应用。在面试中,Java常见面试题是必须要掌握的内容。本文总结了Java常见的10道面试题及其解析,供大家参考。

1. 字符串反转

// 方法1:使用StringBuilder的reverse方法

public static String reverseString1(String str) {

  return new StringBuilder(str).reverse().toString();

}

// 方法2:使用toCharArray()方法和双指针法

public static String reverseString2(String str) {

  char[] s = str.toCharArray();

  int i = 0, j = s.length - 1;

  while (i < j) {

    char temp = s[i];

    s[i++] = s[j];

    s[j--] = temp;

  }

  return new String(s);

}

2. 单例模式

public class Singleton {

  // 私有构造函数

  private Singleton() {}

  // 使用静态内部类的方式实现懒加载

  private static class Holder {

    private static final Singleton INSTANCE = new Singleton();

  }

  // 公有的静态方法获取实例

  public static Singleton getInstance() {

    return Holder.INSTANCE;

  }

}

3. 排序算法

// 冒泡排序

public static void bubbleSort(int[] arr) {

  int length = arr.length;

  for (int i = 0; i < length - 1; i++) {

    for (int j = 0; j < length - i - 1; j++) {

      if (arr[j] > arr[j+1]) {

        int temp = arr[j];

        arr[j] = arr[j+1];

        arr[j+1] = temp;

      }

    }

  }

}

// 快速排序

public static void quickSort(int[] arr, int left, int right) {

  if (left >= right) {

    return;

  }

  int i = left, j = right, pivot = arr[left];

  while (i < j) {

    while (i < j && arr[j] >= pivot) {

      j--;

    }

    arr[i] = arr[j];

    while (i < j && arr[i] <= pivot) {

      i++;

    }

    arr[j] = arr[i];

  }

  arr[i] = pivot;

  quickSort(arr, left, i - 1);

  quickSort(arr, i + 1, right);

}

4. 正则表达式

// 判断字符串是否符合邮箱格式

public static boolean isEmail(String str) {

  String pattern = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";

  return Pattern.matches(pattern, str);

}

// 判断字符串是否符合手机号格式

public static boolean isMobile(String str) {

  String pattern = "1[3-9]\\d{9}";

  return Pattern.matches(pattern, str);

}

5. 实现一个简单的线程池

public class SimpleThreadPool {

  // 线程池中默认的线程数

  private static int DEFAULT_WORKER_NUMBERS = 5;

  // 线程池中最大线程数

  private static int MAX_WORKER_NUMBERS = 10;

  // 线程池中最小线程数

  private static int MIN_WORKER_NUMBERS = 1;

  // 工作列表,用于存储任务

  private final LinkedList jobs = new LinkedList<>();

  // 工作者列表

  private final List workers = Collections.synchronizedList(new ArrayList ());

  // 工作者线程数

  private int workerNum = DEFAULT_WORKER_NUMBERS;

  // 当前激活的线程数

  private AtomicInteger activeWorkerNum = new AtomicInteger();

  // 线程工厂,用于创建线程

  private ThreadFactory threadFactory = new DefaultThreadFactory();

  // 是否关闭线程池

  private volatile boolean isShutdown = false;

  public SimpleThreadPool() {

    initializeWorkers(DEFAULT_WORKER_NUMBERS);

  }

  public void shutdown() {

    isShutdown = true;

    synchronized (jobs) {

      jobs.notifyAll();

    }

    for (Worker worker : workers) {

      try {

        worker.join();

      } catch (InterruptedException e) {

        e.printStackTrace();

      }

    }

  }

  public void submit(Runnable job) {

    if (!isShutdown) {

      synchronized (jobs) {

        jobs.addLast(job);

        jobs.notify();

      }

    }

  }

  public void addWorker(int num) {

    synchronized (jobs) {

      if (num + workerNum > MAX_WORKER_NUMBERS) {

        num = MAX_WORKER_NUMBERS - workerNum;

      }

      initializeWorkers(num);

      this.workerNum += num;

    }

  }

  public void removeWorker(int num) {

    synchronized (jobs) {

      if (num > workerNum) {

        throw new IllegalArgumentException("beyond workNum");

      }

      int count = 0;

      while (count < num) {

        Worker worker = workers.get(count);

        if (workers.remove(worker)) {

          worker.shutdown();

          count++;

        }

      }

      this.workerNum -= num;

    }

  }

  public int getJobSize() {

    return jobs.size();

  }

  private void initializeWorkers(int num) {

    for (int i = 0; i < num; i++) {

      Worker worker = new Worker();

      workers.add(worker);

      Thread thread = threadFactory.createThread(worker);

      thread.start();

    }

  }

  private class Worker implements Runnable {

    private volatile boolean isRunning = true;

    @Override

    public void run() {

      while (isRunning) {

        Runnable job = null;

        synchronized (jobs) {

          while (jobs.isEmpty() && !isShutdown) {

            try {

              jobs.wait();

            } catch (InterruptedException e) {

              e.printStackTrace();

              Thread.currentThread().interrupt();

            }

          }

          if (isShutdown) {

            break;

          }

          job = jobs.removeFirst();

        }

        if (job != null) {

          job.run();

        }

        activeWorkerNum.incrementAndGet();

      }

    }

    public void shutdown() {

      isRunning = false;

    }

  }

  private static class DefaultThreadFactory implements ThreadFactory {

    private static AtomicInteger poolNum = new AtomicInteger(1);

    private final AtomicInteger threadNum = new AtomicInteger(1);

    private final ThreadGroup group;

    private final String prefix;

    public DefaultThreadFactory() {

      SecurityManager securityManager = System.getSecurityManager();

      group = (securityManager != null) ? securityManager.getThreadGroup() :

          Thread.currentThread().getThreadGroup();

      prefix = "pool-" + poolNum.getAndIncrement() + "-thread-";

    }

    @Override

    public Thread createThread(Runnable r) {

      Thread thread = new Thread(group, r, prefix + threadNum.getAndIncrement(), 0);

      if (thread.isDaemon()) {

        thread.setDaemon(false);

      }

      if (thread.getPriority() != Thread.NORM_PRIORITY) {

        thread.setPriority(Thread.NORM_PRIORITY);

      }

      return thread;

    }

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复