Skip to content

Instantly share code, notes, and snippets.

@AhianZhang
Created March 26, 2018 13:29
Show Gist options
  • Save AhianZhang/d3703abc62b0f7a9881b237f4e9d3166 to your computer and use it in GitHub Desktop.
Save AhianZhang/d3703abc62b0f7a9881b237f4e9d3166 to your computer and use it in GitHub Desktop.
java join() 线程
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by AhianZhang on 2018/3/26.
*/
public class ThreadTest
{
public static void main(String[] args)
{
Thread t1 = new MyThread1();
t1.start();
for (int i = 0; i < 16; i++)
{
System.out.println("主线程第" + i + "次执行!");
if (i > 2)
try
{
//分线程合并到主线程中,主线程停止执行过程,转而执行分线程,直到分线程执行完毕后继续。
t1.join();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class MyThread1 extends Thread
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("分线程第" + i + "次执行!");
}
}
}
@AhianZhang
Copy link
Author

主线程第0次执行!
主线程第1次执行!
主线程第2次执行!
主线程第3次执行!
分线程第0次执行!
分线程第1次执行!
分线程第2次执行!
分线程第3次执行!
分线程第4次执行!
主线程第4次执行!
主线程第5次执行!
主线程第6次执行!
主线程第7次执行!
主线程第8次执行!
主线程第9次执行!
主线程第10次执行!
主线程第11次执行!
主线程第12次执行!
主线程第13次执行!
主线程第14次执行!
主线程第15次执行!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment