记录一下使用两个线程交替打印1-100的操作:
/*** @description: 使用两个线程交替打印1-100* @author: Jay* @create: 2024-05-27 21:29**/
public class print_1_to_100 {static volatile int flag = 1; //此处需要加关键字volatile保证变量之间的可见性,否则程序将会阻塞在while循环中动不了(有点类似死锁)。public static void main(String[] args) {new Thread(new thread1()).start();new Thread(new thread2()).start();}
}class thread1 implements Runnable{@Overridepublic void run() {int i = 1;while (i<=99){if(print_1_to_100.flag == 1){System.out.println("线程1: " + i );i += 2;print_1_to_100.flag = 2;}}}
}
class thread2 implements Runnable{@Overridepublic void run() {int i = 2;while (i<=100){if(print_1_to_100.flag == 2){System.out.println("线程2: " + i );i += 2;print_1_to_100.flag = 1;}}}
}
运行结果: