常见的面试算法题:创建几个线程按顺序打印数字或者字母(多线程编程)(套用该模板即可)
比较典型的题目,如下有:
题目一:
1、启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20….以此类推, 直到打印到75。
题目二:
1、使用5个线程
2、五个线程依次打印1A2B…,即第一个线程负责打印1(A、F)等等。
类似这种题目,其实面试官就是想要考验一下你的多线程编程的能力,会在百度、阿里、腾讯、快手、字节这种一线大厂中会经常被问到,就好比想要你写一个生产消费者模型,其实差不多就是想要考验你的多线程编程以及锁的使用的基础,如果写的不是很多,很有可能就会被自己的写的代码给弄蒙的,我之前面试百度的时候给搞蒙了,说到底还是基础不牢,因为平时不太会注重这个地方,所以面试一旦叫你写就会蒙的。
经过这样的一个教训,特意去找了这一系列的面试题目,总结了一个模板,我觉得遇到这样按顺序打印,套用该模板就行,如下:
package PrintLetterInorder;
public class PrintNumsInorder {
public static int count = 0;
public static class MyPrint extends Thread{
int index;
public MyPrint(int index){
this.index = index;
}
public void run(){
synchronized (""){
//这里是顺序打印数字的
//这是题目中的一个终止条件
while(count < 75){
try{
if (count % 3 == (index - 1)){
System.out.println((index - 1)+ "线程打印值为:" + (count + 1));
count++;
"".notifyAll();
}
"".wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
/*这里是顺序打印字母的,对比发现这两个题目的代码只有run()方法中的截止条件有不一样,其他的基本上都一样的,这样就方便在面试过程中去写,不容易乱了。
public void run(){
synchronized (""){
while(count < 26){
try{
//满足打印条件后,打印并将count + 1,然后唤醒其他线程,不满足条件则挂起
if(count % 5 == (index - 1)){
char c = (char)('A' + count);
System.out.println(index + ""+c);
count++;
"".notifyAll();
}
//不满足条件,则挂起
"".wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
*/
}
//利用该主函数直接创建,这个地方题目中要你创建几个,你就创建几个
public static void main(String[] args) {
Thread thread1 = new MyPrint(1);
Thread thread2 = new MyPrint(2);
Thread thread3 = new MyPrint(3);
thread1.start();
thread2.start();
thread3.start();
}
}
输出的结果:
结果1:
结果2: