Android并发编程高级面试题汇总最全最细面试题讲解持续更新中👊👊 👀你想要的面试题这里都有👀 👇👇👇
sleep是可中断的么?(小米)
这道题想考察什么?
是否能够在真实场景中合理运用sleep
考察的知识点
线程管理
考生应该如何回答
sleep是可中断的。
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
// BEGIN Android-changed: Implement sleep() methods using a shared native implementation.
public static void sleep(long millis) throws InterruptedException {
sleep(millis, 0);
}
在现场中
怎么保证线程按顺序执行?如何实现线程排队 ?(金山)
这道题想考察什么?
是否了解多个线程顺序启动的方式有哪些与真实场景使用,是否熟悉多个线程顺序启动在工作中的表现是什么?
考察的知识点
多个线程顺序启动的方式有哪些的概念在项目中使用与基本知识
考生应该如何回答
Q:假设有A、B两个线程,B线程需要在A线程执行完成之后执行。
A:可以在启动B线程之前,调用A线程的join方法,让B线程在A线程执行完成之后启动。
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("执行第一个线程任务!");
}
};
t1.start();
t1.join(); //阻塞等待线程1执行完成
Thread t2 = new Thread() {
@Override
public void run() {
System.out.println("执行第二个线程任务!");
}
};
t2.start();
Q: 假设有A、B两个线程,其中A线程中执行分为3步,需要在A线程执行完成第二步之后再继续执行B线程的代码怎么办?
A:可以使用wait/notify,在B线程中wait,A线程执行完成第二步之后执行notify通知B线程继续执行。
Object lock = new Object();
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("第一步执行完成!");
System.out.println("第二步执行完成!");
synchronized (lock) {
lock.notify();
}
System.out.println("第三步执行完成!");
}
};
Thread t2 = new Thread() {
@Override
public void run() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("执行第二个线程任务!");
}
};
t2.start(); //注意必须先启动t2线程,否则可能t2在notify之后才wait!
t1.start();
Q:假设有A、B、C三个线程,其中A、B线程执行分为三步,C线程需要在A线程执行完第二步后执行一部分代码然后继续等待B线程都执行完第二步时才能执行,怎么办?
A:可以借助CountDownLatch闭锁来完成:
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("t1:第一步执行完成!");
System.out.println("t1:第二步执行完成!");
countDownLatch.countDown();
System.out.println("t1:第三步执行完成!");
}
};
Thread t2 = new Thread() {
@Override
public void run() {
System.out.println("t2:第一步执行完成!");
System.out.println("t2:第二步执行完成!");
countDownLatch.countDown();
System.out.println("t2:第三步执行完成!");
}
};
Thread t3 = new Thread() {
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行第三个线程任务!");
};
t3.start();
t2.start();
t1.start();