Thread thread2=new Thread(new ThreadUseRunnable(),"SecondThread");"SecondThread"是参数传递下去吗|?run()如何获取到这个值?
2 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
Runnable里面没有传参函数,所以得自己造一个
0.自定义一个接口,继承Runnable,新增一个传参方法
public interface MyRunnable extends Runnable{ public MyRunnable setParam(String... param); } |
实现这个自定义接口
MyRunnable sendMessage = new MyRunnable() { String message; @Override public MyRunnable setParam(String... param) { message = param[ 0 ]; return this ; } @Override public void run() { sendMessage(message); } }; |
2.初始化线程池,运行Runnable
ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); cachedThreadPool.execute(sendMessage.setParam( "I am service" )); |
如上所示,线程池调用的一个runnable实例,这个runnable实例传入了一个字符串参数
添加回答
举报
0/150
提交
取消