线程同步和线程join

2023-10-30  本文已影响0人  皓皓amous
public class TestThreadActivity extends AppCompatActivity {
   private String TAG = "TestThreadActivity";
   private Thread threadSon;

   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.testthreadlayout);
       initView();
       initListen();

   }

   public class ThreadRunnable implements Runnable {
       @Override
       public void run() {
           synchronized (ThreadRunnable.this) {
               for (int i = 0; i < 15; i++) {
                   try {
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   Log.d(TAG, "testSQ" + Thread.currentThread().getName() + " i: " + i);
               }
           }
       }
   }


   private void initListen() {

   }

   private void initView() {
       Button btn = findViewById(R.id.btn);
       btn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
//                ThreadRunnable threadRunnable = new ThreadRunnable();
//                new Thread(threadRunnable, "张三").start();
//                new Thread(threadRunnable, "李四").start();
//                new Thread(threadRunnable, "王五").start();
               joinThread();
           }
       });
   }

   public void joinThread() {
       TestRunableJoin testRunableJoin = new TestRunableJoin();
       Thread threadFather = new Thread(new Runnable() {
           @Override
           public void run() {
               for (int i = 0; i < 15; i++) {
                   Log.d(TAG, "testsq:" + "father " + Thread.currentThread().getName() + " " + i);
                   try {
                       Thread.sleep(300);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }

//                  todo 子线程
                   try {
                       threadSon.join();
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   threadSon.start();

               }
           }
       }, "zhansan");
       threadFather.start();
       threadSon = new Thread(testRunableJoin, "lise");
   }


   public class TestRunableJoin implements Runnable {
       @Override
       public void run() {
           for (int i = 0; i < 15; i++) {
               Log.d(TAG, "testsq: son" + Thread.currentThread().getName() + " " + i);
               try {
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
       }
   }

}

线程join 流程示意:


线程join.png
上一篇下一篇

猜你喜欢

热点阅读