package LockThread;
public class Test extends Thread {
private static int currentCount = 0;
public Test(String name) {
this.setName(name);
}
@Override
public void run() {
while (currentCount < 30) {
switch (currentCount % 3) {
case 0:
if ("A".equals(getName())) {
printAndIncrease();
}
break;
case 1:
if ("B".equals(getName())) {
printAndIncrease();
}
break;
case 2:
if ("C".equals(getName())) {
printAndIncrease();
}
break;
}
}
}
private void printAndIncrease() {
print();
increase();
}
private void print() {
System.out.println(getName());
if ("C".equals(getName())) {
System.out.println();
}
}
private void increase() {
currentCount++;
}
public static void main(String[] args) {
new Test("A").start();
new Test("B").start();
new Test("C").start();
}
}
以上是我在网上看到的某个方法,说是用sleep方法实现,但是我在代码里却没看见sleep()方法,而且他是用继承Thread生成3个独立的线程,每个线程count都是循环30次,实际每个打印10次,但是他这个程序怎么保证,线程按序打印的呢,我测试了下 运行确实是正确的