多个线程轮流输出的解法
多线程一道非常经典的面试题就是两个或者三个线程轮流按照题目要求去进行轮流输出,这个题目其实将其中的思路理清楚之后就会变的很简单;
总体的思路其实很简单,我们根据题目的要求去写出需要的线程,然后每个不同线程中的run方法中的方法可以写在一个中间类中去分别进行调用(思路和消费者生产者线程案例中的中间类一样),然后我们就需要控制的题目的输出条件,我们可以根据变量的值去判断(比如布尔类型或者int类型)当线程得到资源的时候去执行的时候,这个线程里面的方法的输出是否符合题目给出的要求,换句话说,当还不需要A线程去进行输出的时候,A线程却得到了资源,所以我们这个时候就需要对每个线程中的方法再额外加上“一个锁”,看看A线程执行的时间是否正确;
第二个需要注意的点就是我们再测试多线程的时候常常用的方法就是用for循环让方法执行多次,但是根据上面的原理其实和乐观锁的原理是有一点点相似的(如果有多个线程的话,难免会出现进入的线程和题目要求不符合的情况,但是我们可以根据上面提到的变量去修改线程,最后的结果是和题目要求是一致的,但是某一个线程有可能会执行了多次,但是没有输入而已),所以我们很有可能会发现想要输出10个值的时候,总是输出不够;所以我们在唤醒线程的时候可以让一个变量自增,然后让这个变量作为run方法中的循环判断标准。
当然作为菜鸟这个方法更多的是思路上较为简单,可以遇到相似问题的时候套用过来当作模板 下面附上练习代码 不标准 互喷
public class Test2 {
public static MidClass midClass=new MidClass();
static class A extends Thread{
@Override
public void run() {
while(midClass.sysAnum<3){
try {
midClass.sysA("A");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class B extends Thread{
@Override
public void run() {
while(midClass.sysBnum<3){
try {
midClass.sysB("B");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class C extends Thread {
@Override
public void run() {
while(midClass.sysCnum<3){
try {
midClass.sysC("C");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
public class MidClass {
private int aBoolean=1;
public int sysAnum=0;
public int sysBnum=0;
public int sysCnum=0;
public synchronized void sysA(String str) throws InterruptedException {
if (aBoolean ==1){
notifyAll();
System.out.println(str);
aBoolean=2;
sysAnum++;
}else{
wait();
}
}
public synchronized void sysB(String str) throws InterruptedException {
if (aBoolean ==2){
notifyAll();
System.out.println(str);
aBoolean=3;
sysBnum++;
}else{
wait();
}
}
public synchronized void sysC(String str) throws InterruptedException {
if (aBoolean ==3){
notifyAll();
System.out.println(str);
aBoolean=1;
sysCnum++;
}else{
wait();
}
}
}
浙公网安备 33010602011771号