//利用两个线程实现1到100的计算
public class MyRannable implements java.lang.Runnable{
private Thread th_0;
private Thread th_2;
int sum=0;//存储累加和的结果
int i=1;
public void run(){
String thName=Thread.currentThread().getName();//获取当前线程的名字
while (i<=101){
System.out.println( "当前线程"+thName+"正在计算" );
System.out.println( "当前的累加和" +sum);
sum+=i++;
if(i==50&&thName.equals( "线程1" )){
break;
}
try {
Thread.sleep( 100 );
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public MyRannable(Thread t0,Thread t2){
if(t0==null){
th_0=new Thread( this );//th0和th2共享一个实现runnable的实例
}
if(t2==null){
th_2=new Thread( this );
}
th_0.setName( "线程1" );
th_2.setName( "线程2" );
th_0.start();//启动线程t0
try {
th_0.join();
}catch (InterruptedException e){
e.printStackTrace();
}
th_2.start();
}
}测试类
public class test106 {
public static void main(String[] args){
//Thread t0=new Thread( );
//t0.setName( "线程1" );
//Thread t2=new Thread( );
//t2.setName( "线程2" );
Thread t0=null;
Thread t2=null;
MyRannable ran=new MyRannable( t0,t2 );
}
}
运行结果