Java常见的面试算法题:实现两个线程交替打印1到100的数
- 思路:
这是涉及到多个线程打印的问题,一定会用到锁的(synchronized),故这就是一个多线程打印的典型案例。
- 代码实现:
package Test;
public class DoubleThreadPrint {
public static int count = 0;
public static class MyPrint extends Thread{
//定义一个整型变量来标识线程
int index;
public MyPrint(int index){
this.index = index;
}
//重写run方法
@Override
public void run() {
//获取锁
synchronized (""){
while(count < 100){
try {
if(count % 2 == index - 1){
System.out.println((index - 1) + "线程打印值为:" + (count + 1));
count++;
"".notifyAll();
}
//释放锁
"".wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread t1 = new MyPrint(1);
Thread t2 = new MyPrint(2);
t1.start();
t2.start();
}
}
- 运行结果: