java多线程结合单例模式实例,简单实用易理解

最近接触到多线程,为了弄清原理,写了以下代码:


新建以下类:

 /**
 * 多线程执行顺序测试
 * 
 */
public class ThreadTest {
public static void main(String[]args) throws InterruptedException{

for(int i = 0;i<1;i++){
  // if(i==0){
     new DataDeal().dealData(String.valueOf(i));
 //  }
System.out.println("主线程:i="+i);
System.out.println("主线程显示子线程此时的数据是:子线程"+DataDeal.threadNumOfDataDeal+DataDeal.sonR);
//Thread.sleep(1000);
}
for(int j=0;j<20;j++){
Thread.sleep(2000);
//System.out.println("主线程显示子线程此时的数据是..:子线程"+DataDeal.threadNumOfDataDeal+DataDeal.sonR);
System.out.println("主线程显示子线程此时的数据是..:子线程"+DataDeal.threadNumOfDataDeal+Result.getInstance().getSonThreadr());
//判断子线程运行状态,“0”表示子线程运行结束,如果子线程运行结束,则主线程跳出循环显示,也结束
if(Result.getInstance().getSonTheadState().equals("0")){
break;
}
}
System.out.println("主线程执行完毕");
}
}


public class DataDeal {
public static String sonR;
public static String threadNumOfDataDeal;
private String threadNum2;
public void dealData(String threadNum){
threadNumOfDataDeal = threadNum;
this.threadNum2 = threadNum;
new Thread(new Runnable(){
public void run(){
Result.getInstance().setSonTheadState("1");//将子线程运行状态设为“1”,表示子线程启动
try {
for(int i = 0;i<5;i++){
for(int j = 0;j<5;j++){
Thread.sleep(1000);
sonR = "["+i+"]["+j+"]";
Result.getInstance().setSonThreadr("["+i+"]["+j+"]");
//System.out.println("子线程"+threadNum2+"。。。。。。"+sonR);

}
}
System.out.println("子线程"+threadNum2+"执行完毕");
Result.getInstance().setSonTheadState("0");//将子线程运行状态设为“0”,表示子线程运行结束
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("子线程异常");
Result.getInstance().setSonTheadState("0");//将子线程运行状态设为“0”,表示子线程运行结束
}
}
}).start();
}
}


public class Result {
private String sonThreadr;//子线程运行时数据
private String sonTheadState;//子线程运行状态:0运行结束;1正在运行

//采用单例模式
private Result(){}
private static Result r;

public static Result getInstance(){
if(r == null)
r = new Result();
return r;
}


public String getSonTheadState() {
return sonTheadState;
}


public void setSonTheadState(String sonTheadState) {
this.sonTheadState = sonTheadState;
}


public String getSonThreadr() {
return sonThreadr;
}


public void setSonThreadr(String sonThreadr) {
this.sonThreadr = sonThreadr;
}

}


你可能感兴趣的:(java多线程结合单例模式实例,简单实用易理解)