1.synchronized
lock为锁对象,order为1表示线程1可以打印,为2表示线程2可以打印,为3表示线程3可以打印
num表示打印的次数
public class PrintThread(){
private static Object lock = new Object();
private static int order = 1;
private static int num = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
num = in.nextInt();
Thread thread1 = new Thread() {
@Override
public void run() {
while (num > 0) {
synchronized (lock){
if (num > 0 && order == 1){
System.out.print("a");
order++;
}
}
}
}
};
Thread thread2 = new Thread() {
@Override
public void run() {
while (num > 0) {
synchronized (lock){
if (num > 0 && order == 2){
System.out.print("l");
order++;
}
}
}
}
};
Thread thread3 = new Thread() {
@Override
public void run() {
while (num > 0) {
synchronized (lock){
if (num > 0 && order == 3){
System.out.println("i");
order = 1;
num--;
}
}
}
}
};
thread1.start();
thread2.