[Java] java 多线程 →→→→→进入此内容的聊天室

来自 , 2020-07-13, 写在 Java, 查看 151 次.
URL http://www.code666.cn/view/17326d10
  1. package concurrent;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. public class TestThreadPool {
  5. public static void main(String args[]) throws InterruptedException {
  6. // only two threads
  7. ExecutorService exec = Executors.newFixedThreadPool(2);
  8. for(int index = 0; index < 100; index++) {
  9. Runnable run = new Runnable() {
  10. public void run() {
  11. long time = (long) (Math.random() * 1000);
  12. System.out.println(“Sleeping ” + time + “ms”);
  13. try {
  14. Thread.sleep(time);
  15. } catch (InterruptedException e) {
  16. }
  17. }
  18. };
  19. exec.execute(run);
  20. }
  21. // must shutdown
  22. exec.shutdown();
  23. }
  24. }//源代码片段来自云代码http://yuncode.net
  25.  
  26. package concurrent;
  27. import static java.util.concurrent.TimeUnit.SECONDS;
  28. import java.util.Date;
  29. import java.util.concurrent.Executors;
  30. import java.util.concurrent.ScheduledExecutorService;
  31. import java.util.concurrent.ScheduledFuture;
  32. public class TestScheduledThread {
  33. public static void main(String[] args) {
  34. final ScheduledExecutorService scheduler = Executors
  35. .newScheduledThreadPool(2);
  36. final Runnable beeper = new Runnable() {
  37. int count = 0;
  38. public void run() {
  39. System.out.println(new Date() + ” beep ” + (++count));
  40. }
  41. };
  42. // 1秒钟后运行,并每隔2秒运行一次
  43. final ScheduledFuture beeperHandle = scheduler.scheduleAtFixedRate(
  44. beeper, 1, 2, SECONDS);
  45. // 2秒钟后运行,并每次在上次任务运行完后等待5秒后重新运行
  46. final ScheduledFuture beeperHandle2 = scheduler
  47. .scheduleWithFixedDelay(beeper, 2, 5, SECONDS);
  48. // 30秒后结束关闭任务,并且关闭Scheduler
  49. scheduler.schedule(new Runnable() {
  50. public void run() {
  51. beeperHandle.cancel(true);
  52. beeperHandle2.cancel(true);
  53. scheduler.shutdown();
  54. }
  55. }, 30, SECONDS);
  56. }
  57. }//源代码片段来自云代码http://yuncode.net
  58.                        
  59.                        
  60.  
  61. package concurrent;
  62. import java.text.SimpleDateFormat;
  63. import java.util.Date;
  64. import java.util.concurrent.BrokenBarrierException;
  65. import java.util.concurrent.CyclicBarrier;
  66. import java.util.concurrent.ExecutorService;
  67. import java.util.concurrent.Executors;
  68. public class TestCyclicBarrier {
  69. // 徒步需要的时间: Shenzhen, Guangzhou, Shaoguan, Changsha, Wuhan
  70. private static int[] timeWalk = { 5, 8, 15, 15, 10 };
  71. // 自驾游
  72. private static int[] timeSelf = { 1, 3, 4, 4, 5 };
  73. // 旅游大巴
  74. private static int[] timeBus = { 2, 4, 6, 6, 7 };
  75.  
  76. static String now() {
  77. SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm:ss”);
  78. return sdf.format(new Date()) +:;
  79. }
  80. static class Tour implements Runnable {
  81. private int[] times;
  82. private CyclicBarrier barrier;
  83. private String tourName;
  84. public Tour(CyclicBarrier barrier, String tourName, int[] times) {
  85. this.times = times;
  86. this.tourName = tourName;
  87. this.barrier = barrier;
  88. }
  89. public void run() {
  90. try {
  91. Thread.sleep(times[0] * 1000);
  92. System.out.println(now() + tourName + ” Reached Shenzhen”);
  93. barrier.await();
  94. Thread.sleep(times[1] * 1000);
  95. System.out.println(now() + tourName + ” Reached Guangzhou”);
  96. barrier.await();
  97. Thread.sleep(times[2] * 1000);
  98. System.out.println(now() + tourName + ” Reached Shaoguan”);
  99. barrier.await();
  100. Thread.sleep(times[3] * 1000);
  101. System.out.println(now() + tourName + ” Reached Changsha”);
  102. barrier.await();
  103. Thread.sleep(times[4] * 1000);
  104. System.out.println(now() + tourName + ” Reached Wuhan”);
  105. barrier.await();
  106. } catch (InterruptedException e) {
  107. } catch (BrokenBarrierException e) {
  108. }
  109. }
  110. }
  111.  
  112. public static void main(String[] args) {
  113. // 三个旅行团
  114. CyclicBarrier barrier = new CyclicBarrier(3);
  115. ExecutorService exec = Executors.newFixedThreadPool(3);
  116. exec.submit(new Tour(barrier, “WalkTour”, timeWalk));
  117. exec.submit(new Tour(barrier, “SelfTour”, timeSelf));
  118. exec.submit(new Tour(barrier, “BusTour”, timeBus));
  119. exec.shutdown();
  120. }
  121. }//源代码片段来自云代码http://yuncode.net
  122.                        
  123.  
  124. package concurrent;
  125. import java.io.File;
  126. import java.io.FileFilter;
  127. import java.util.concurrent.BlockingQueue;
  128. import java.util.concurrent.ExecutorService;
  129. import java.util.concurrent.Executors;
  130. import java.util.concurrent.LinkedBlockingQueue;
  131. import java.util.concurrent.atomic.AtomicInteger;
  132.  
  133. public class TestBlockingQueue {
  134. static long randomTime() {
  135. return (long) (Math.random() * 1000);
  136. }
  137.  
  138. public static void main(String[] args) {
  139. // 能容纳100个文件
  140. final BlockingQueue queue = new LinkedBlockingQueue(100);
  141. // 线程池
  142. final ExecutorService exec = Executors.newFixedThreadPool(5);
  143. final File root = new File(“F:\\JavaLib”);
  144. // 完成标志
  145. final File exitFile = new File(“”);
  146. // 读个数
  147. final AtomicInteger rc = new AtomicInteger();
  148. // 写个数
  149. final AtomicInteger wc = new AtomicInteger();
  150. // 读线程
  151. Runnable read = new Runnable() {
  152. public void run() {
  153. scanFile(root);
  154. scanFile(exitFile);
  155. }
  156.  
  157. public void scanFile(File file) {
  158. if (file.isDirectory()) {
  159. File[] files = file.listFiles(new FileFilter() {
  160. public boolean accept(File pathname) {
  161. return pathname.isDirectory()
  162. || pathname.getPath().endsWith(“.java);
  163. }
  164. });
  165. for (File one : files)
  166. scanFile(one);
  167. } else {
  168. try {
  169. int index = rc.incrementAndGet();
  170. System.out.println(“Read0:+ index + ” “
  171. + file.getPath());
  172. queue.put(file);
  173. } catch (InterruptedException e) {
  174. }
  175. }
  176. }
  177. };
  178. exec.submit(read);
  179. // 四个写线程
  180. for (int index = 0; index < 4; index++) {
  181. // write thread
  182. final int NO = index;
  183. Runnable write = new Runnable() {
  184. String threadName = “Write” + NO;
  185. public void run() {
  186. while (true) {
  187. try {
  188. Thread.sleep(randomTime());
  189. int index = wc.incrementAndGet();
  190. File file = queue.take();
  191. // 队列已经无对象
  192. if (file == exitFile) {
  193. // 再次添加”标志”,以让其他线程正常退出
  194. queue.put(exitFile);
  195. break;
  196. }
  197. System.out.println(threadName +:+ index + ” “
  198. + file.getPath());
  199. } catch (InterruptedException e) {
  200. }
  201. }
  202. }
  203. };
  204. exec.submit(write);
  205. }
  206. exec.shutdown();
  207. }
  208. }//源代码片段来自云代码http://yuncode.net
  209.                        
  210.  
  211.  
  212. package concurrent;
  213. import java.util.concurrent.CountDownLatch;
  214. import java.util.concurrent.ExecutorService;
  215. import java.util.concurrent.Executors;
  216.  
  217. public class TestCountDownLatch {
  218. public static void main(String[] args) throws InterruptedException {
  219. // 开始的倒数锁
  220. final CountDownLatch begin = new CountDownLatch(1);
  221. // 结束的倒数锁
  222. final CountDownLatch end = new CountDownLatch(10);
  223. // 十名选手
  224. final ExecutorService exec = Executors.newFixedThreadPool(10);
  225. for(int index = 0; index < 10; index++) {
  226. final int NO = index + 1;
  227. Runnable run = new Runnable(){
  228. public void run() {
  229. try {
  230. begin.await();
  231. Thread.sleep((long) (Math.random() * 10000));
  232. System.out.println(“No.” + NO + ” arrived”);
  233. } catch (InterruptedException e) {
  234. } finally {
  235. end.countDown();
  236. }
  237. }
  238. };
  239. exec.submit(run);
  240. }
  241. System.out.println(“Game Start”);
  242. begin.countDown();
  243. end.await();
  244. System.out.println(“Game Over”);
  245. exec.shutdown();
  246. }
  247. }//源代码片段来自云代码http://yuncode.net
  248.        
  249.  
  250.  
  251.  
  252. package concurrent;
  253. import java.util.concurrent.Callable;
  254. import java.util.concurrent.ExecutionException;
  255. import java.util.concurrent.ExecutorService;
  256. import java.util.concurrent.Executors;
  257. import java.util.concurrent.Future;
  258.  
  259. public class TestFutureTask {
  260. public static void main(String[] args)throws InterruptedException,
  261. ExecutionException {
  262. final ExecutorService exec = Executors.newFixedThreadPool(5);
  263. Callable call = new Callable() {
  264. public String call() throws Exception {
  265. Thread.sleep(1000 * 5);
  266. return “Other less important but longtime things.”;
  267. }
  268. };
  269. Future task = exec.submit(call);
  270. // 重要的事情
  271. Thread.sleep(1000 * 3);
  272. System.out.println(“Let’s do important things.”);
  273. // 其他不重要的事情
  274. String obj = task.get();
  275. System.out.println(obj);
  276. // 关闭线程池
  277. exec.shutdown();
  278. }
  279. }//源代码片段来自云代码http://yuncode.net
  280.                                        
  281.  
  282. package concurrent;
  283. import java.util.concurrent.Callable;
  284. import java.util.concurrent.CompletionService;
  285. import java.util.concurrent.ExecutionException;
  286. import java.util.concurrent.ExecutorCompletionService;
  287. import java.util.concurrent.ExecutorService;
  288. import java.util.concurrent.Executors;
  289. import java.util.concurrent.Future;
  290.  
  291. public class TestCompletionService {
  292. public static void main(String[] args) throws InterruptedException,
  293. ExecutionException {
  294. ExecutorService exec = Executors.newFixedThreadPool(10);
  295. CompletionService serv =
  296. new ExecutorCompletionService(exec);
  297.  
  298. for (int index = 0; index < 5; index++) {
  299. final int NO = index;
  300. Callable downImg = new Callable() {
  301. public String call() throws Exception {
  302. Thread.sleep((long) (Math.random() * 10000));
  303. return “Downloaded Image+ NO;
  304. }
  305. };
  306. serv.submit(downImg);
  307. }
  308.  
  309. Thread.sleep(1000 * 2);
  310. System.out.println(“Show web content”);
  311. for (int index = 0; index < 5; index++) {
  312. Future task = serv.take();
  313. String img = task.get();
  314. System.out.println(img);
  315. }
  316. System.out.println(“End”);
  317. // 关闭线程池
  318. exec.shutdown();
  319. }
  320. }//源代码片段来自云代码http://yuncode.net
  321.                        
  322.  
  323. package concurrent;
  324. import java.util.concurrent.ExecutorService;
  325. import java.util.concurrent.Executors;
  326. import java.util.concurrent.Semaphore;
  327.  
  328. public class TestSemaphore {
  329. public static void main(String[] args) {
  330. // 线程池
  331. ExecutorService exec = Executors.newCachedThreadPool();
  332. // 只能5个线程同时访问
  333. final Semaphore semp = new Semaphore(5);
  334. // 模拟20个客户端访问
  335. for (int index = 0; index < 20; index++) {
  336. final int NO = index;
  337. Runnable run = new Runnable() {
  338. public void run() {
  339. try {
  340. // 获取许可
  341. semp.acquire();
  342. System.out.println(“Accessing:+ NO);
  343. Thread.sleep((long) (Math.random() * 10000));
  344. // 访问完后,释放
  345. semp.release();
  346. } catch (InterruptedException e) {
  347. }
  348. }
  349. };
  350. exec.execute(run);
  351. }
  352. // 退出线程池
  353. exec.shutdown();
  354. }
  355. }//源代码片段来自云代码http://yuncode.net
  356.                        
  357.  
  358.  
  359.  
  360.  
  361.  

回复 "java 多线程"

这儿你可以回复上面这条便签

captcha