java并发面试题整理

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/StemQ/article/details/56494704

1.java中有几种方法可以实现一个线程?

1).需要从Java.lang.Thread类派生一个新的线程类,重载它的run()方法;

public class MyThread extends Thread {
	@Override
	public void run() {
		super.run();
		System.out.println("Hello World !" + Thread.currentThread().getName());
	}
}

public static void main(String[] args) {
	MyThread thread1 = new MyThread();
	MyThread thread2 = new MyThread();
	thread1.start();
	thread2.start();
}

2).实现Runnalbe接口,重载Runnalbe接口中的run()方法;

public class MyThread implements Runnable {
	@Override
	public void run() {
		System.out.println("Hello World !" + Thread.currentThread().getName());
	}
}
public static void main(String[] args) {
     MyThread thread1 = new MyThread();
     MyThread thread2 = new MyThread();
     Thread t1=new Thread(thread1);
     Thread t2=new Thread(thread2);
     t1.start();
     t2.start();
}

3).使用ExecutorService、Callable、Future实现有返回结果的线程.

	public static void main(String[] args) {
		// 创建一个线程池
		ExecutorService threadPool = Executors.newCachedThreadPool();
		// 执行任务并获取Future对象
		Future<String> future = threadPool.submit(new Callable<String>() {
			public String call() {
				return "Hello World !";
			}
		});
		// 关闭线程池
		threadPool.shutdown();
		try {
			// get方法是阻塞的。即:线程无返回结果,get方法会一直等待。
			System.out.println("result->" + future.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}

2.notify()和notifyAll()有什么区别?

1).notify()方法表示,当前的线程已经放弃对资源的占有,只是让一个线程从wait中恢复过来,然后继续运行wait()后面的语句。

2).notifyAll()方法表示,当前的线程已经放弃对资源的占有,让所有的线程从wait中恢复过来,通知所有的等待线程从wait()方法后的语句开始运行。

先到这,明天我继续整理....

猜你喜欢

转载自blog.csdn.net/StemQ/article/details/56494704