package com.example.demo;
import org.junit.Test;
import com.example.demo.JoinMain.AddThread;
/**
* join() 方法,线程无限制的等待
* public final synchronized void join(long millis) 指定等待时间,到达时间就不会继续等待
* 下面方法如果不加上join()方法时候,打印出来的可能是0;但是加上后就变成了1000;
* @author Administrator
*
*/
public class JoinMain {
public volatile static int i = 0;
public static class AddThread extends Thread {
@Override
public void run() {
for(i= 0; i < 1000; i++);
}
}
@Test
public void main() throws InterruptedException {
AddThread addThread = new AddThread();
addThread.start();
addThread.join();
System.out.println(i);
}
}
package com.example.demo;
import org.junit.Test;
/**
* 线程组
* @author Administrator
*
* 打印信息
2
I am PrintGroup-T2
java.lang.ThreadGroup[name=PrintGroup,maxpri=10]
I am PrintGroup-T1
Thread[T1,5,PrintGroup]
Thread[T2,5,PrintGroup]
*/
public class ThreadGroupName implements Runnable {
@Test
public void testThreadGroup() {
// 创建 PrintGroup 线程组,并且把T1,T2加入线程组
ThreadGroup tg = new ThreadGroup("PrintGroup");
Thread t1 = new Thread(tg, new ThreadGroupName(), "T1");
Thread t2 = new Thread(tg, new ThreadGroupName(), "T2");
t1.start();
t2.start();
// activeCount() 方法可以获取到活动线程的总数,估计值,无法确定精确
System.out.println(tg.activeCount());
// list() 方法可以打印这个线程组所有线程信息
tg.list();
}
@Override
public void run() {
String groupAndName = Thread.currentThread().getThreadGroup().getName() +
"-" + Thread.currentThread().getName();
while (true) {
System.out.println("I am " + groupAndName);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}