遇到一个问题,最主要的是能把这个问题,进行转换,转换成我们熟悉的问题。
很多大厂会问这种实际类型的问题,如果在实际应用中用的较少,基本很难写出来,代码较基础,但是如果在面试中,那种环境下一旦写出来是很加分项。
在代码中会经常运用到多线程,多线程的实现问题,以及触发死锁的具体代码实现。
目录
一、使用多线程--交替打印数字问题
1、main函数创建两个线程,并进行启动
public class Test{
public static void main(String[] args){
Number number = new Number();
Thread thread1 = new Thread(number);
Thread thread2 = new Thread(number);
thread1.setName("线程【1】");
thread2.setName("线程【2】");
thread1.start();
thread2.start();
}
}
2、多线程具体实现打印内容
class Number implements Runnable{
private int number = 1;
@Override
public void run(){
while(true){
synchronized(this){
this.notify();
if(number<=10){
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("线程名称"+Thread.currentThread().getName()+",number="+number);
number++;
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
}