上QQ阅读APP看书,第一时间看更新
1.1.12 多进路-多处理-多出路实验
本实现的目标是允许多个线程同时处理任务,更具体来讲,也就是每个线程都在处理自己的任务。
创建实验用的项目Semaphore_MoreToOne_1,类Service.java代码如下:
package service; import java.util.concurrent.Semaphore; public class Service { private Semaphore semaphore = new Semaphore(3); void sayHello() { try { semaphore.acquire(); System.out.println("ThreadName=" + Thread.currentThread().getName() + "准备"); System.out.println("begin hello " + System.currentTimeMillis()); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "打印" + (i + 1)); } System.out.println(" end hello " + System.currentTimeMillis()); semaphore.release(); System.out.println("ThreadName=" + Thread.currentThread().getName() + "结束"); } catch (InterruptedException e) { e.printStackTrace(); } } }
线程类MyThread.java代码如下:
package extthread; import service.Service; public class MyThread extends Thread { private Service service; public MyThread(Service service) { super(); this.service = service; } @Override public void run() { service.sayHello(); } }
运行类Run.java代码如下:
package test.run; import service.Service; import extthread.MyThread; Public class Run { public static void main(String[] args) { Service service = new Service(); MyThread[] threadArray = new MyThread[12]; for (int i = 0; i < threadArray.length; i++) { threadArray[i] = new MyThread(service); threadArray[i].start(); } } }
程序运行结果如图1-24所示。
图1-24 打印循环中的内容为乱序
运行的效果是多个线程同时进入,而多个线程又几乎同时执行完毕。