- public class Main{
- public static boolean flag;
- public static void main(String[] args) {
- T t = new T(true);
- int counts=0;
- flag = false;
- t.start();
- while(counts++<50){
- while(!flag){};//flage为真时继续向下执行
- System.out.println("主线程第"+counts+"次");
- for(int i=1;i<=100;i++){
- System.out.println("主线程:"+i);
- }
- t.set();//设置子线程的flag为真,让子线程继续向下执行
- flag = false;//让主线程在
- }
- }
- }
- class T extends Thread{
- Boolean flag = null;
- int counts = 0;
- T(boolean b){
- flag = b;
- }
- public void set(){
- flag = !flag;
- }
- @Override
- public void run() {
- while(counts++<50){
- while(!flag){}//flag为真时继续向下执行,当主线程中改变此值时。
- System.out.println("子线程第"+counts+"次");
- for(int i=1;i<=10;i++){
- System.out.println("子线程:"+i);
- }
- flag = false;//让子线程在下个while处反复执行
- Main.flag = true;//让主线程继续向下执行
- }
- }
- }
复制代码 |