我将从Java基础、集合、多线程等多个重要方面,为你呈现一线互联网大厂最新的高质量Java面试八股文及答案,帮助你高效备考。
import java.util.Scanner;
public class CalculatorProcedure {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数字: ");
double num1 = scanner.nextDouble();
System.out.print("请输入操作符(+, -, *, /): ");
char operator = scanner.next().charAt(0);
System.out.print("请输入第二个数字: ");
double num2 = scanner.nextDouble();
double result = 0;
switch(operator) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
System.out.println("无效的操作符");
return;
}
System.out.println("计算结果: " + result);
}
public static double add(double a, double b) {
return a + b;
}
public static double subtract(double a, double b) {
return a - b;
}
public static double multiply(double a, double b) {
return a * b;
}
public static double divide(double a, double b) {
if(b == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return a / b;
}
}
import java.util.Scanner;
interface Operation {
double calculate(double num1, double num2);
}
class Addition implements Operation {
@Override
public double calculate(double num1, double num2) {
return num1 + num2;
}
}
class Subtraction implements Operation {
@Override
public double calculate(double num1, double num2) {
return num1 - num2;
}
}
class Multiplication implements Operation {
@Override
public double calculate(double num1, double num2) {
return num1 * num2;
}
}
class Division implements Operation {
@Override
public double calculate(double num1, double num2) {
if(num2 == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return num1 / num2;
}
}
class Calculator {
public double performOperation(double num1, double num2, Operation operation) {
return operation.calculate(num1, num2);
}
}
public class CalculatorObject {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数字: ");
double num1 = scanner.nextDouble();
System.out.print("请输入操作符(+, -, *, /): ");
char operator = scanner.next().charAt(0);
System.out.print("请输入第二个数字: ");
double num2 = scanner.nextDouble();
Calculator calculator = new Calculator();
Operation operation = getOperation(operator);
double result = calculator.performOperation(num1, num2, operation);
System.out.println("计算结果: " + result);
}
private static Operation getOperation(char operator) {
switch(operator) {
case '+':
return new Addition();
case '-':
return new Subtraction();
case '*':
return new Multiplication();
case '/':
return new Division();
default:
throw new IllegalArgumentException("无效的操作符: " + operator);
}
}
}
public class EqualsVsIdentity {
public static void main(String[] args) {
// 基本数据类型比较
int a = 10;
int b = 10;
System.out.println("基本数据类型 == 比较: " + (a == b)); // true
// 引用数据类型比较
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println("引用数据类型 == 比较: " + (s1 == s2)); // false
System.out.println("引用数据类型 equals 比较: " + s1.equals(s2)); // true
// 自定义对象比较
User user1 = new User("张三", 20);
User user2 = new User("张三", 20);
System.out.println("自定义对象 == 比较: " + (user1 == user2)); // false
System.out.println("自定义对象 equals 比较: " + user1.equals(user2)); // true
// 未重写equals方法的对象比较
Person person1 = new Person("李四", 30);
Person person2 = new Person("李四", 30);
System.out.println("未重写equals的对象 == 比较: " + (person1 == person2)); // false
System.out.println("未重写equals的对象 equals 比较: " + person1.equals(person2)); // false
}
}
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null || getClass() != obj.getClass()) return false;
User other = (User) obj;
return this.name.equals(other.name) && this.age == other.age;
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
import java.util.ArrayList;
import java.util.List;
public class FinalExample {
// 静态常量
public static final double PI = 3.14159;
public static void main(String[] args) {
// final修饰基本数据类型
final int num = 10;
// num = 20; // 编译错误,不能修改final变量
// final修饰引用数据类型
final List<String> list = new ArrayList<>();
list.add("hello"); // 可以修改引用对象的内容
// list = new ArrayList<>(); // 编译错误,不能修改引用
// final修饰方法
Child child = new Child();
child.print(); // 调用父类的final方法
// final修饰类
// class MyString extends String {} // 编译错误,String是final类,不能被继承
}
}
class Parent {
public final void print() {
System.out.println("Parent method");
}
}
class Child extends Parent {
// public void print() {} // 编译错误,不能重写final方法
}
public class StaticExample {
// 静态变量
public static int count = 0;
// 实例变量
public int id;
public StaticExample() {
count++;
id = count;
}
// 静态方法
public static void printCount() {
System.out.println("Count: " + count);
// System.out.println(id); // 编译错误,静态方法不能访问实例变量
}
// 静态代码块
static {
System.out.println("静态代码块执行");
}
// 实例代码块
{
System.out.println("实例代码块执行,id: " + id);
}
public static void main(String[] args) {
System.out.println("main方法开始");
StaticExample.printCount(); // 直接通过类名调用静态方法
StaticExample s1 = new StaticExample();
StaticExample s2 = new StaticExample();
System.out.println("s1.id: " + s1.id);
System.out.println("s2.id: " + s2.id);
StaticExample.printCount();
}
}
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ArrayListVsLinkedList {
public static void main(String[] args) {
int size = 100000;
// 测试ArrayList随机访问性能
List<Integer> arrayList = new ArrayList<>();
for(int i = 0; i < size; i++) {
arrayList.add(i);
}
long startTime = System.currentTimeMillis();
for(int i = 0; i < size; i++) {
arrayList.get(i);
}
long endTime = System.currentTimeMillis();
System.out.println("ArrayList随机访问耗时: " + (endTime - startTime) + "ms");
// 测试LinkedList随机访问性能
List<Integer> linkedList = new LinkedList<>();
for(int i = 0; i < size; i++) {
linkedList.add(i);
}
startTime = System.currentTimeMillis();
for(int i = 0; i < size; i++) {
linkedList.get(i);
}
endTime = System.currentTimeMillis();
System.out.println("LinkedList随机访问耗时: " + (endTime - startTime) + "ms");
// 测试ArrayList插入性能
arrayList = new ArrayList<>();
startTime = System.currentTimeMillis();
for(int i = 0; i < size; i++) {
arrayList.add(0, i);
}
endTime = System.currentTimeMillis();
System.out.println("ArrayList头部插入耗时: " + (endTime - startTime) + "ms");
// 测试LinkedList插入性能
linkedList = new LinkedList<>();
startTime = System.currentTimeMillis();
for(int i = 0; i < size; i++) {
linkedList.add(0, i);
}
endTime = System.currentTimeMillis();
System.out.println("LinkedList头部插入耗时: " + (endTime - startTime) + "ms");
}
}
import java.util.LinkedList;
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private LinkedList<Entry<K, V>>[] table;
public MyHashMap() {
table = new LinkedList[DEFAULT_CAPACITY];
for(int i = 0; i < DEFAULT_CAPACITY; i++) {
table[i] = new LinkedList<>();
}
}
public void put(K key, V value) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = table[index];
for(Entry<K, V> entry : bucket) {
if(entry.key.equals(key)) {
entry.value = value;
return;
}
}
bucket.add(new Entry<>(key, value));
}
public V get(K key) {
int index = getIndex(key);
LinkedList<Entry<K, V>> bucket = table[index];
for(Entry<K, V> entry : bucket) {
if(entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
private int getIndex(K key) {
if(key == null) return 0;
return Math.abs(key.hashCode()) % table.length;
}
static class Entry<K, V> {
K key;
V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
System.out.println("apple: " + map.get("apple"));
System.out.println("banana: " + map.get("banana"));
System.out.println("cherry: " + map.get("cherry"));
System.out.println("date: " + map.get("date"));
}
}
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class HashMapVsHashtable {
public static void main(String[] args) throws InterruptedException {
int threadCount = 10;
int loopCount = 1000;
// 测试HashMap在多线程环境下的表现
Map<Integer, Integer> hashMap = new HashMap<>();
ExecutorService executor1 = Executors.newFixedThreadPool(threadCount);
long startTime = System.currentTimeMillis();
for(int i = 0; i < threadCount; i++) {
executor1.execute(() -> {
for(int j = 0; j < loopCount; j++) {
hashMap.put(j, j);
}
});
}
executor1.shutdown();
executor1.awaitTermination(1, TimeUnit.MINUTES);
long endTime = System.currentTimeMillis();
System.out.println("HashMap耗时: " + (endTime - startTime) + "ms, 大小: " + hashMap.size());
// 测试Hashtable在多线程环境下的表现
Map<Integer, Integer> hashtable = new Hashtable<>();
ExecutorService executor2 = Executors.newFixedThreadPool(threadCount);
startTime = System.currentTimeMillis();
for(int i = 0; i < threadCount; i++) {
executor2.execute(() -> {
for(int j = 0; j < loopCount; j++) {
hashtable.put(j, j);
}
});
}
executor2.shutdown();
executor2.awaitTermination(1, TimeUnit.MINUTES);
endTime = System.currentTimeMillis();
System.out.println("Hashtable耗时: " + (endTime - startTime) + "ms, 大小: " + hashtable.size());
}
}
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadSafeCollections {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5;
int loopCount = 1000;
// Vector示例
List<Integer> vector = new Vector<>();
ExecutorService executor1 = Executors.newFixedThreadPool(threadCount);
for(int i = 0; i < threadCount; i++) {
executor1.execute(() -> {
for(int j = 0; j < loopCount; j++) {
vector.add(j);
}
});
}
executor1.shutdown();
executor1.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Vector大小: " + vector.size());
// Hashtable示例
Map<Integer, Integer> hashtable = new Hashtable<>();
ExecutorService executor2 = Executors.newFixedThreadPool(threadCount);
for(int i = 0; i < threadCount; i++) {
executor2.execute(() -> {
for(int j = 0; j < loopCount; j++) {
hashtable.put(j, j);
}
});
}
executor2.shutdown();
executor2.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Hashtable大小: " + hashtable.size());
// ConcurrentHashMap示例
Map<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<>();
ExecutorService executor3 = Executors.newFixedThreadPool(threadCount);
for(int i = 0; i < threadCount; i++) {
executor3.execute(() -> {
for(int j = 0; j < loopCount; j++) {
concurrentHashMap.put(j, j);
}
});
}
executor3.shutdown();
executor3.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("ConcurrentHashMap大小: " + concurrentHashMap.size());
// CopyOnWriteArrayList示例
List<Integer> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
ExecutorService executor4 = Executors.newFixedThreadPool(threadCount);
for(int i = 0; i < threadCount; i++) {
executor4.execute(() -> {
for(int j = 0; j < loopCount; j++) {
copyOnWriteArrayList.add(j);
}
});
}
executor4.shutdown();
executor4.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("CopyOnWriteArrayList大小: " + copyOnWriteArrayList.size());
}
}
// 方式一:继承Thread类
class MyThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println("继承Thread类的线程: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 方式二:实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println("实现Runnable接口的线程: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 方式三:实现Callable接口
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for(int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
public class CreateThreads {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 方式一:继承Thread类
MyThread thread1 = new MyThread();
thread1.start();
// 方式二:实现Runnable接口
MyRunnable runnable = new MyRunnable();
Thread thread2 = new Thread(runnable);
thread2.start();
// 方式三:实现Callable接口
MyCallable callable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread3 = new Thread(futureTask);
thread3.start();
// 获取Callable线程的返回值
Integer result = futureTask.get();
System.out.println("Callable线程计算结果: " + result);
// 主线程继续执行
for(int i = 0; i < 5; i++) {
System.out.println("主线程: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadStateExample {
public static void main(String[] args) throws InterruptedException {
Thread target = new Thread(() -> {
System.out.println("线程状态: " + Thread.currentThread().getState());
try {
// 线程进入TIMED_WAITING状态
Thread.sleep(2000);
System.out.println("线程休眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ThreadStateExample.class) {
try {
// 线程进入WAITING状态
ThreadStateExample.class.wait();
System.out.println("线程被唤醒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程继续执行");
});
// 输出新建状态
System.out.println("新建状态: " + target.getState());
// 启动线程,进入RUNNABLE状态
target.start();
System.out.println("启动后状态: " + target.getState());
// 主线程休眠3秒,让目标线程有足够时间休眠
Thread.sleep(3000);
System.out.println("休眠3秒后状态: " + target.getState());
// 唤醒目标线程
synchronized (ThreadStateExample.class) {
ThreadStateExample.class.notify();
}
// 主线程休眠1秒,让目标线程有时间被唤醒
Thread.sleep(1000);
System.out.println("唤醒后状态: " + target.getState());
// 等待目标线程执行完毕
target.join();
System.out.println("线程结束后状态: " + target.getState());
}
}
public class ContextSwitchSimulation {
private static final int THREAD_COUNT = 10;
private static final int LOOP_COUNT = 1000000;
public static void main(String[] args) throws InterruptedException {
// 创建多个线程模拟上下文切换
Thread[] threads = new Thread[THREAD_COUNT];
for(int i = 0; i < THREAD_COUNT; i++) {
final int index = i;
threads[i] = new Thread(() -> {
for(int j = 0; j < LOOP_COUNT; j++) {
// 简单的计算操作
Math.sqrt(Math.random() * 100);
}
System.out.println("线程 " + index + " 执行完毕");
});
}
long startTime = System.currentTimeMillis();
// 启动所有线程
for(Thread thread : threads) {
thread.start();
}
// 等待所有线程执行完毕
for(Thread thread : threads) {
thread.join();
}
long endTime = System.currentTimeMillis();
System.out.println("所有线程执行完毕,耗时: " + (endTime - startTime) + "ms");
}
}
public class DeadlockExample {
private static final Object resource1 = new Object();
private static final Object resource2 = new Object();
public static void main(String[] args) {
// 创建线程1
Thread thread1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("线程1获取了资源1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1尝试获取资源2");
synchronized (resource2) {
System.out.println("线程1获取了资源2");
}
}
});
// 创建线程2
Thread thread2 = new Thread(() -> {
synchronized (resource2) {
System.out.println("线程2获取了资源2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2尝试获取资源1");
synchronized (resource1) {
System.out.println("线程2获取了资源1");
}
}
});
// 启动线程
thread1.start();
thread2.start();
// 主线程等待一段时间后检查线程状态
try {
Thread.sleep(2000);
System.out.println("线程1状态: " + thread1.getState());
System.out.println("线程2状态: " + thread2.getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 避免死锁的示例
class DeadlockAvoidance {
private static final Object resource1 = new Object();
private static final Object resource2 = new Object();
public static void main(String[] args) {
// 创建线程1 - 按照相同顺序获取锁
Thread thread1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("线程1获取了资源1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1尝试获取资源2");
synchronized (resource2) {
System.out.println("线程1获取了资源2");
}
}
});
// 创建线程2 - 按照相同顺序获取锁
Thread thread2 = new Thread(() -> {
synchronized (resource1) {
System.out.println("线程2获取了资源1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2尝试获取资源2");
synchronized (resource2) {
System.out.println("线程2获取了资源2");
}
}
});
// 启动线程
thread1.start();
thread2.start();
// 主线程等待线程执行完毕
try {
thread1.join();
thread2.join();
System.out.println("所有线程正常执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
":"load_by_key","id":"","key":"banner_image_0","width":0,"height":0,"image_type":"search","pages_id":"8142750540428034","genre":"技术文章","artifact_key":8141877036422146}]()
面向过程:注重解决问题的步骤和过程,按步骤顺序执行方法,将数据和操作分离。例如实现一个简单的计算器功能,面向过程会按照输入数字、选择运算符号、进行运算、输出结果这样的步骤来编写代码。其优点是效率高,无需类加载和对象实例化;缺点是程序耦合度高,维护和扩展困难。
面向对象:注重对象,将数据和操作封装在对象中,通过对象之间的交互来解决问题。还是以计算器为例,会抽象出数字对象、运算符号对象、计算器对象等,每个对象有自己的属性和方法,通过调用对象的方法来完成计算。优点是程序易维护、易复用、易扩展;缺点是相比面向过程效率更低,因为需要类加载和对象实例化。
==:比较的是变量(栈)内存中存放的对象的(堆)内存地址,用来判断两个对象是否是同一个对象。对于基本数据类型,比较的是值;对于引用数据类型,比较的是内存地址。例如:
int a = 10;
int b = 10;
System.out.println(a == b); // 输出true,因为基本数据类型比较值
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // 输出false,因为s1和s2是不同的对象,内存地址不同
equals:用来比较两个对象的内容是否相等。所有类都继承自java.lang.Object类,如果没有重写equals方法,调用的是Object类中的equals方法,其内部实现还是使用==来比较内存地址。通常我们会根据业务需求在自定义类中重写equals方法。例如在自定义的User类中,如果我们认为两个User对象只要用户名和密码相同就相等,就可以重写equals方法:
public class User {
private String username;
private String password;
// 省略构造函数、getter和setter方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(username, user.username) &&
Objects.equals(password, user.password);
}
}
final int num = 10;
num = 20; // 编译错误,不能修改final修饰的基本数据类型变量
final List<String> list = new ArrayList<>();
list.add("hello"); // 可以,虽然list引用不能改变,但可以操作其内部元素
list = new ArrayList<>(); // 编译错误,不能改变final修饰的引用类型变量的引用
public class StaticExample {
static int staticVar = 10;
int instanceVar = 20;
public static void main(String[] args) {
StaticExample s1 = new StaticExample();
StaticExample s2 = new StaticExample();
s1.staticVar = 30;
System.out.println(s2.staticVar); // 输出30,因为静态变量是共享的
System.out.println(s1.instanceVar); // 输出20
System.out.println(s2.instanceVar); // 输出20,实例变量每个对象都有自己的一份
}
}
public class StaticMethodExample {
static void staticMethod() {
System.out.println("这是一个静态方法");
}
void instanceMethod() {
System.out.println("这是一个实例方法");
}
public static void main(String[] args) {
StaticMethodExample.staticMethod(); // 直接通过类名调用静态方法
StaticMethodExample s = new StaticMethodExample();
s.instanceMethod(); // 通过对象调用实例方法
}
}
public class StaticBlockExample {
static int staticVar;
static {
staticVar = 100;
System.out.println("静态代码块执行");
}
public static void main(String[] args) {
System.out.println(StaticBlockExample.staticVar); // 输出100
}
}
finally块中的代码无论try块中是否发生异常,也无论try块中是否有return语句,都会执行(除了在finally块之前JVM退出的情况)。不过如果try块中有return语句,会先执行return语句中的表达式,将结果暂存,然后执行finally块中的代码,最后再返回之前暂存的结果。例如:
public class TryCatchFinallyExample {
public static int test() {
try {
return 1;
} finally {
System.out.println("finally块执行");
}
}
public static void main(String[] args) {
int result = test();
System.out.println(result); // 输出:finally块执行 1
}
}
在上述代码中,try块中的return语句先将1暂存,然后执行finally块中的代码输出“finally块执行”,最后返回暂存的1。
HashMap基于哈希表实现,使用数组和链表(JDK1.8及之后引入红黑树)来存储数据。其工作原理如下:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
假设“apple”计算出的哈希值对应的数组索引为3,且该位置为空,就将“apple”和1存入数组索引为3的位置。如果“banana”计算出的哈希值也对应数组索引为3,那么就将“banana”和2以链表形式插入到索引为3位置已有的元素后面。
Integer value = map.get("apple");
System.out.println(value); // 输出1
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put(null, 1);
hashMap.put("key", null);
Hashtable的键和值都不能为null,如果尝试插入null键或null值会抛出NullPointerException。
Vector<Integer> vector = new Vector<>();
vector.add(1);
多个线程同时调用add方法不会出现数据不一致问题。
ConcurrentHashMap<String, Integer> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("key1", 1);
Integer value = concurrentHashMap.get("key1");
可以高效地在多线程环境下工作。
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
list.add(1);
int size = list.size();
多个线程同时进行读操作不会受写操作影响。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行中:" + Thread.currentThread().getName());
}
}
public class ThreadCreationExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程执行中:" + Thread.currentThread().getName());
}
}
public class RunnableCreationExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("线程执行中:" + Thread.currentThread().getName());
return 100;
}
}
public class CallableCreationExample {
public static void main(String[] args) throws Exception {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
Integer result = futureTask.get();
System.out.println("线程返回结果:" + result);
}
}
Thread thread = new Thread();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
线程上下文切换是指当CPU从一个线程切换到另一个线程执行时,需要保存当前线程的上下文信息(包括寄存器的值、程序计数器的值、栈指针等),并恢复要切换到的线程的上下文信息,以便该线程能够继续正确执行。例如,当一个线程在执行过程中,时间片用完,操作系统会将其上下文信息保存到内存中,然后从就绪队列中选择另一个线程,将该线程的上下文信息从内存中读取出来并恢复到CPU寄存器等硬件中,从而让新的线程开始执行。线程上下文切换会带来一定的开销,频繁的上下文切换会影响系统性能。
死锁是指两个或两个以上的线程在执行过程中,因争夺资源而造成的一种互相等待的现象,如果没有外力干涉,这些线程将永远无法继续执行。例如,线程A持有资源1,等待获取资源2,而线程B持有资源2,等待获取资源1,此时两个线程就陷入了死锁。
避免死锁的方法:
2025 年,一线互联网大厂,Java
资源地址:
https://pan.quark.cn/s/14fcf913bae6
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有