常见的 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.t2.start(); //this starts the 2nd thread. This calls the run() method. }}123456789101112131415class Counter extends Base implements Runnable{//method where the thread execution will start public void run(){//logic to execute in a thread }//let us see how to start the threadspublic static void main(String[] args){Thread t1 = new Thread(new Counter());Thread t2 = new Thread(new Counter());t1.start(); //start the first thread. This calls the run() method.t2.start(); //this starts the 2nd thread. This calls the run() method. }} 通过线程池来创建更有效率。 问题:推举通过哪种方式创建线程,为什么? 解答:最好使用 Runnable 接口,这样你的类就不必继承Thread 类,不然当你需要多重继承的时候,你将 一筹莫展(我们都知道 Java 中的类只能继承自一个类,但可以同时实现多个接口)。在上面的例子中,因为我们要继承 Base 类,所以实现 Runnable 接口成了显而易见的选择。同时你也要注意到在不同的...