java159-两个线程共同完成1到100计算
//利用两个线程实现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 );
}
}
运行结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!