首先是线程的创建和jion()方法的使用。
class Sleeper extends Thread
{
private int sleeptime;
public Sleeper(String name,int sleepTime)
{
super(name);
sleeptime=sleepTime;
start();
}
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println(getName()+"print"+i);
sleep(sleeptime);
}
}catch(InterruptedException e)
{
System.out.println(getName()+"interrupted");
}
System.out.println(getName()+" over");
}
}
class Joiner extends Thread
{
private Sleeper sleeper;
public Joiner(String name,Sleeper sleeper)
{
super(name);
this.sleeper=sleeper;
start();
}
public void run()
{
try
{
System.out.println(getName()+" Begin");
System.out.println(sleeper.getName()+"begin jion()....");
sleeper.join();
for(int i=5;i>0;i--)
{
System.out.println(getName()+"print:"+i);
}
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println(getName()+"Over!");
}
}
public class SimpleJoin {
public static void main(String[] args)
{
Sleeper sleeper1=new Sleeper("Tread A sleeper1",1500),
sleeper2=new Sleeper("Tread A sleeper2",1000);
Joiner joiner=new Joiner("ThreadB",sleeper2);
sleeper1.interrupt();
//System.out.println("Hello");
}
}
创建三个Tread,第三个jion了第二个。
运行结果:
Tread A sleeper1print0
Tread A sleeper2print0
Tread A sleeper1interrupted
Tread A sleeper1 over
ThreadB Begin
Tread A sleeper2begin jion()....
Tread A sleeper2print1
Tread A sleeper2print2
Tread A sleeper2print3
Tread A sleeper2print4
Tread A sleeper2 over
ThreadBprint:5
ThreadBprint:4
ThreadBprint:3
ThreadBprint:2
ThreadBprint:1
ThreadBOver!