Java多线程常见面试问题及解答
问题:进程和线程的区别
解答:一个进程对应一个程序的执行,而一个线程则是进程执行过程中的一个单独的执行序列,一个进程可以包含多个线程,
Java多线程常见面试问题及解答
。线程有时候也被称为轻量级进程.一个Java虚拟机的实例运行在一个单独的进程中,不同的线程共享Java虚拟机进程所属的堆内存。这也是为什么不同的线程可以访问同一个对象。线 程彼此共享堆内存并保有他们自己独自的栈空间。这也是为什么当一个线程调用一个方法时,他的.局部变量可以保证线程安全。但堆内存并不是线程安全的,必须通 过显示的声明同步来确保线程安全。
问题:列举几种不同的创建线程的方法.
解答:可以通过如下几种方式:
• 继承Thread 类
• 实现Runnable 接口
• 使用Executor framework (这会创建一个线程池)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class
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 threads
public
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.
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class
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 threads
public
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.
}
}
通过线程池来创建更有效率,
资料共享平台
《Java多线程常见面试问题及解答》(https://www.unjs.com)。问题:推荐通过哪种方式创建线程,为什么?
解答:最好使用Runnable接口,这样你的类就不必继承Thread类,不然当你需要多重继承的时候,你将 一筹莫展(我们都知道Java中的类只能继承自一个类,但可以同时实现多个接口)。在上面的例子中,因为我们要继承Base类,所以实现Runnable 接口成了显而易见的选择。同时你也要注意到在不同的例子中,线程是如何启动的。按照面向对象的方法论,你应该只在希望改变父类的行为的时候才去继承他。通 过实现Runnable接口来代替继承Thread类可以告诉使用者Counter是Base类型的一个对象,并会作为线程执行。
问题:简要的说明一下高级线程状态.
解答:下图说明了线程的各种状态.
• 可执行(Runnable):当调用start()方法后,一个线程变为可执行状态,但是并不意味着他会立刻开始真正地执行。而是被放入线程池,
【Java多线程常见面试问题及解答】相关文章:
3.常见面试问题解答