我们知道多线程是通过star()方法让线程处于准备就绪状态,而实际运行的业务逻辑是放在run()方法体中的,但是run()方法是没有参数的方法,实际的业务场景中,我们可能需要向方法体中传递参数,下面介绍常用的两种传参方式,第三种下次再说,或者你们百度吧,这里偷个懒。
第一种方式:构造方法传参
public class CallbackCustomerTypeThread implements Runnable
{
public static final Logger logger = LoggerFactory.getLogger(CallbackCustomerTypeThread.class);
private BasCmCustomerType basCmCustomerType;
private BasCmCustomerTypeService basCmCustomerTypeService;
public CallbackCustomerTypeThread(BasCmCustomerType basCmCustomerType, BasCmCustomerTypeService basCmCustomerTypeService)
{
this.basCmCustomerType = basCmCustomerType;
this.basCmCustomerTypeService = basCmCustomerTypeService;
}
@Override
public void run()
{
//向金剑南同步
try
{
basCmCustomerTypeService.syncToJjn(basCmCustomerType);
}
catch (Exception e)
{
logger.info("向金剑南同步客户异常,id=" + basCmCustomerType.getId(), e);
}
//向水晶剑同步
try
{
basCmCustomerTypeService.syncToSjj(basCmCustomerType);
}
catch (Exception e)
{
logger.info("向水晶剑同步客户异常,id=" + basCmCustomerType.getId(), e);
}
}
}
调用:
Runnable runnable = new CallbackCustomerTypeThread(basCmCustomerType, this);
Thread thread = new Thread(runnable);
thread.start();
第二种方式:通过变量或者方法传递参数
package mythread;
public class MyThread2 implements Runnable
{
private String name;
public void setName(String name)
{
this.name = name;
}
public void run()
{
System.out.println("hello " + name);
}
public static void main(String[] args)
{
MyThread2 myThread = new MyThread2();
myThread.setName("world");
Thread thread = new Thread(myThread);
thread.start();
}
}
第三种:通过回调函数传递参数
暂时不写了,滴~~~~ 下班卡