zl程序教程

您现在的位置是:首页 >  后端

当前栏目

写线程三步骤Thread

线程 步骤 thread
2023-09-14 09:04:30 时间

1、声明

private Thread th;

2、写线程,将需要线程的代码放进去,可能是两三句就可以了的,记得写th.start();

th=new Thread(new Runnable() { //两个new,还要一个Runnable
@Override
public void run() {
Map maps=new HashMap<>(); //需要线程的内容
maps.put(“开始时间”,startTime+" 结束时间="+endTime); //需要线程的内容
try {
new AppConnectInfo().goTestInfo(“51”, “4”, “save”, maps); //需要线程的内容,这个需要try catch,写完后会自动让你加的
} catch (Exception e) {
e.printStackTrace();
}
}
});th.start();

2、最后要销毁线程

public void onDestroy(){
    super.onDestroy();
    if(th!=null)
        th=null;
    releaseAll();
}
public void releaseAll() {
    MyLoger.d(tag, "释放资源");

}

写方法的四个步骤:

1、谁的对象:Thread th
2、对象的作用范围: private Thread th
3、然后就可以使用这个对象了,比如说创建一个线程:th=new Thread(new Runnable() { }
或者是一个方法:public int daysBetween(Date smdate, Date bdate) throws Exception {}
4、最后就是要启动线程:th.start();还要销毁线程
或者是调用这个方法:if ((daysBetween(nowtimes, startTime1)) > 2) {}

形参和实参:形参就是方法里面的,只是一个壳,一个模子;实参就调用这个方法,传一个真实的值

形参实例:AppConnectInofo中的一个方法
public String goTestInfo(String id, String num, String wheres, Map<String, String> map) throws Exception {
Map<String, String> bundle = new HashMap<>();
bundle.put(“功能序号”, id);
bundle.put(“业务序号”, num);
bundle.put(“操作类型”, wheres);
bundle.put(“args”, JSON.toJSONString(map));
String url = SERVER_DOMAIN + “/terminal/api/facade/demo”;
String reString = requestProtocol(url, reSetParmas(bundle), HttpUtility.HTTPMETHOD_POST);
return reString;
}

实参实例:
Map maps=new HashMap<>();
maps.put(“开始时间”,startTime);
maps.put(“结束时间”,endTime);
new AppConnectInfo().goTestInfo(“58”, “4”, “save”,maps); //调用了AppConnectInfo类里面的goTestInfo方法,(“58”, “4”, “save”,maps)就是实参,传过去给goTestInfo,goTestInfo就用这些参数通过自己的方法体然后实现这个方法的功能