资源预览内容
第1页 / 共5页
第2页 / 共5页
第3页 / 共5页
第4页 / 共5页
第5页 / 共5页
亲,该文档总共5页全部预览完了,如果喜欢就下载吧!
资源描述
多线程传参及多线程并发量控制多线程传参多线程传参的控制有两种:假设有线程类如下:Public class MyThreadprivate int arg1;pirvate String arg2;Setters;Getters;pubic MyThread()super();public MuThread(int ar1,String ar2)this.arg1 = ar1;this.arg2 = ar2;1.构造方法通过在新建线程的时候,将参数传入到子线程构造函数中例如:for(int I = 0 ; I 100 ; I+)MyThread mt = new MyThread(参数1,参数2);Thread td = new Thread(t);Td.start();2.属性设置通过在新建线程的时候,将参数Set到子线程的属性中例如:for(int I = 0 ; I 100 ; I+)MyThread mt = new MyThread();mt.setArg1(参数1);mt.setArg2(参数2);Thread td = new Thread(t);td.start();并发量控制并发量的控制可以通过java中的并发信号量来控制示例代码import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class TestSemaphore public static void main(String args) / 线程池ExecutorService exec = Executors.newCachedThreadPool();/ 只能个线程同时访问final Semaphore semp = new Semaphore(5);for (int index = 1; index 21; index+) final int NO = index;Runnable run = new Runnable() public void run() try / 获取许可semp.acquire();System.out.println(Accessing: + NO);Thread.sleep(long) (Math.random() * 1000);/ 访问完后,释放System.out.println(Release: + NO);semp.release(); catch (InterruptedException e) ;exec.execute(run);/ 退出线程池exec.shutdown();混合代码代码import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class TestWait implements Runnable /当前信号量int nt = 0;/线程池ExecutorService service = null;/全局信号量Semaphore sp = null;public ExecutorService getService() return service;public void setService(ExecutorService service) this.service = service;public Semaphore getSp() return sp;public void setSp(Semaphore sp) this.sp = sp;public int getNt() return nt;public void setNt(int nt) this.nt = nt;public static void main(String args) /线程池ExecutorService tservice = Executors.newCachedThreadPool();/设定多线程并发信号量final Semaphore tsp = new Semaphore(10);int cnt = 100;for (int i = 1; i thread No. + nt + start ! * 还有 +sp.getQueueLength()+ 线程等待执行);try Thread.sleep(1000); catch (InterruptedException e1) e1.printStackTrace();try/线程减数sp.release();catch(Exception e)e.printStackTrace();
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号