多线程2

发布时间 2023-04-03 21:22:10作者: 越狱兔狲

Join

//join线程强制执行(插队)
public class TestJoin implements Runnable{
   @Override
   public void run() {
       for (int i = 0; i < 100; i++) {

           System.out.println("我是vip==》"+i);
      }
  }

   public static void main(String[] args) throws InterruptedException {
       TestJoin testJoin = new TestJoin();
       Thread thread=new Thread(testJoin);
       thread.start();

       for (int i = 0; i < 50; i++) {
           System.out.println("main"+i);
           if (i==10){
               thread.join();
          }
      }
  }
}
 

线程停止

//建议线程正常停止,利用次数,不建议死循环
//建议使用标志位。设置一个标志位flag
//不要使用stop或者destroy等果实或者jdk不建议使用的方法
public class TestStop implements Runnable{
   private boolean flag=true;
   @Override
   public void run() {
       int i=0;
       while (flag) {
           System.out.println("Thread正在奔跑===》"+i++);
      }
  }

   public void stop(){
       flag=false;
  }
   public static void main(String[] args) {

       TestStop testStop = new TestStop();
       new Thread(testStop).start();

       for (int i = 0; i < 1000; i++) {
           System.out.println("main===>"+i);
           if (i==900){
               testStop.stop();
               System.out.println("线程该停止了");
          }
      }


  }
}