一些线程相关的问题
来源:互联网 发布:匿名免费发短信软件 编辑:程序博客网 时间:2024/06/05 19:54
题目:
8个运动员同时起跑,都到达终点后记录成绩
实现:
package com.spring.test;import java.util.Random;import java.util.concurrent.CountDownLatch;/** * Created by brady on 15-3-1. */public class CountDownLatchTest implements Runnable{ private int id; private CountDownLatch beginSingnal; private CountDownLatch endSingnal; public CountDownLatchTest(int id ,CountDownLatch beginSingnal,CountDownLatch endSingnal){ this.id = id; this.beginSingnal = beginSingnal; this.endSingnal = endSingnal; } @Override public void run(){ try{ beginSingnal.await(); Random random = new Random(); Thread.sleep(Math.abs(random.nextInt())%100); endSingnal.countDown(); System.out.println("我到了:" + this.id); }catch (InterruptedException e){ e.printStackTrace(); } } public static void main(String[] args){ CountDownLatch beginSingnal = new CountDownLatch(1); CountDownLatch endSingnal = new CountDownLatch(8); for(int i=1;i<=8;i++){ new Thread(new CountDownLatchTest(i,beginSingnal,endSingnal)).start(); } beginSingnal.countDown(); try { endSingnal.await(); } catch (InterruptedException e) { e.printStackTrace(); } }}
两个线程循环打印
package com.spring.test;/** * Created by brady on 15-3-13. *//* * 两个线程循环打印 */public class WaitNotify { private static final Object a = new Object(); private static boolean x1 = true; private static boolean y1 = false; private static final int x = 30; private static int y = 1; public static void main(String[] args){ Thread t1 = new Thread(){ public void run(){ synchronized (a){ while (!x1) try { a.wait(); } catch (InterruptedException e) { e.printStackTrace(); } while (y<x){ for(int i=0;i<3;i++){ System.out.println("线程一:" + y++); } x1=false; y1=true; a.notify(); } } } }; Thread t2 = new Thread(){ public void run(){ synchronized (a){ while (!y1) try { a.wait(); } catch (InterruptedException e) { e.printStackTrace(); } while (y<x){ for(int i=0;i<3;i++){ System.out.println("线程二:" + y++); } y1=false; x1=true; a.notify(); } } } }; t1.start(); t2.start(); }}
0 0
- 一些线程相关的问题
- 线程相关的一些问题
- 线程相关的一些记录
- 线程以及一些线程相关的事物
- java线程的相关问题
- 和线程安全相关的一些技术
- 和线程安全相关的一些技术
- facanf相关的一些问题
- localhost的一些相关问题
- gson的一些相关问题
- AlertDialog的一些相关问题
- phpstudy相关的一些问题
- windows线程挂起与唤醒,SuspendThread与ResumeThread的一些相关问题
- 关于线程的一些问题
- .Net线程的一些问题
- 线程一些相关函数
- Qt的一些坐标相关的问题
- 线程同步,锁的相关问题
- Java4Android学习十六 - equals()、hashCode()、toString()
- 内存管理小结
- c++之参数传递
- linux常用命令2
- Linux mmap
- 一些线程相关的问题
- grub启动命令行学习(一)
- UVa 246 - 10-20-30 [STL应用]
- iOS项目上传到AppStore步骤流程
- OSG下的引用计数指针(Reference Pointers)的理解
- 【8】香干炒肉丝
- 边界路由器如何实现网络负载均衡
- Essay
- HDU 2971解题报告