金九银十快要来了,整理了50道多线程并发面试题,大家可以点赞、收藏起来,慢慢品!~
选择多线程的原因,就是因为快。举个例子:
如果要把1000块砖搬到楼顶,假设到楼顶有几个电梯,你觉得用一个电梯搬运快,还是同时用几个电梯同时搬运快呢?这个电梯就可以理解为线程。

所以,我们使用多线程就是因为:在正确的场景下,设置恰当数目的线程,可以用来程提高序的运行速率。更专业点讲,就是充分地利用CPU和I/O的利用率,提升程序运行速率。
当然,有利就有弊,多线程场景下,我们要保证线程安全,就需要考虑加锁。加锁如果不恰当,就很很耗性能。

Java中创建线程主要有以下这几种方式:
public class ThreadTest {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
@Override
public void run() {
System.out.println("111");
}
}
public class ThreadTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("111");
}
}
//运行结果:
如果想要执行的线程有返回,可以使用Callable。
public class ThreadTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThreadCallable mc = new MyThreadCallable();
FutureTask ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
}
class MyThreadCallable implements Callable {
@Override
public String call()throws Exception {
return "111";
}
}
//运行结果:
111
日常开发中,我们一般都是用线程池的方式执行异步任务。
public class ThreadTest {
public static void main(String[] args) throws Exception {
ThreadPoolExecutor executorOne = new ThreadPoolExecutor(5, 5, 1,
TimeUnit.MINUTES, new ArrayBlockingQueue(20), new CustomizableThreadFactory("Tianluo-Thread-pool"));
executorOne.execute(() -> {
System.out.println("111");
});
//关闭线程池
executorOne.shutdown();
}
}
其实start和run的主要区别如下:
大家可以结合代码例子来看看哈~
public class ThreadTest {
public static void main(String[] args){
Thread t=new Thread(){
public void run(){
pong();
}