常见的 Java 多线程面试问题及解答 解答:一个进程对应一个程序的执行,而一个线程则是进程执行过程中的一个单独的执行序列,一个进程可以包含多个线程
线程有时候也被称为轻量级进程
一个 Java 虚拟机的实例运行在一个单独的进程中,不同的线程共享 Java 虚拟机进程所属的堆内存
这也是为什么不同的线程可以访问同一个对象
线 程彼此共享堆内存并保有他们自己独自的栈空间
这也是为什么当一个线程调用一个方法时,他的局部变量可以保证线程安全
但堆内存并不是线程安全的,必须通 过显示的声明同步来确保线程安全
问题:列举几种不同的创建线程的方法
解答:可以通过如下几种方式: 继承 Thread 类 实现 Runnable 接口 使用 Executor framework (这会创建一个线程池) 123456789101112131415class Counter extends Thread {//method where the thread execution will start public void run(){//logic to execute in a thread }//let’s see how to start the threadspublic static void main(String[] args){Thread t1 = new Counter();Thread t2 = new Counter();t1
start(); //start the first thread
This calls the run() method
start(); //this starts the 2nd thread
This calls the run() method
}}123456789101112131415class Counter e