如果你即将去一家从事大型系统研发的公司进行Java面试,不可避免的会有多线程相关的问题。下面是一些针对初学者或者新手的问题,如果你已经具备良好的基础,那么你可以跳过本文,直接尝试针对进阶水平的Java多线程编程问题及解答。
解答:一个进程对应一个程序的执行,而一个线程则是进程执行过程中的一个单独的执行序列,一个进程可以包含多个线程。线程有时候也被称为轻量级进程.
一个Java虚拟机的实例运行在一个单独的进程中,不同的线程共享Java虚拟机进程所属的堆内存。这也是为什么不同的线程可以访问同一个对象。线程彼此共 享堆内存并保有他们自己独自的栈空间。这也是为什么当一个线程调用一个方法时,他的局部变量可以保证线程安全。但堆内存并不是线程安全的,必须通过显示的声明同步来确保线程安全。
解答:可以通过如下几种方式:
继承Thread类
实现Runnable接口
使用Executorframework(这会创建一个线程池)

- classCounter extendsThread {
- //method where the thread execution will start
- publicvoidrun(){
- //logic to execute in a thread
- }
- //let’s see how to start the threads
- publicstaticvoidmain(String[] args){
- Thread t1 = newCounter();
- Thread t2 = newCounter();
- t1.start(); //start the first thread. This calls the run() method.
- t2.start(); //this starts the 2nd thread. This calls the run() method.
- classCounter extendsBase implementsRunnable{
- //method where the thread execution will start
- publicvoidrun(){
- //logic to execute in a thread
- }
- //let us see how to start the threads
- publicstaticvoidmain(String[] args){
- Thread t1 = newThread(newCounter());
- Thread t2 = newThread(newCounter());
- t1.start(); //start the first thread. This calls the run() method.
- t2.start(); //this starts the 2nd thread. This calls the run() method.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-32846-1.html
12海里指的是哪里
你这不是自己在打自己的脸吗