- package test11;
- package test11;
- /*题目1:编写一个多线程程序,每隔30ms输出线程的名字(线程至少3个以上)【多线程】。
- */
- public class ThreadTest {
- public static void main(String[] args) {
- TimeMillis tm=new TimeMillis();
- MyThread mt1=new MyThread(tm);
- MyThread mt2=new MyThread(tm);
- MyThread mt3=new MyThread(tm);
- MyThread mt4=new MyThread(tm);
- MyThread mt5=new MyThread(tm);
- new Thread(mt1).start();
- new Thread(mt2).start();
- new Thread(mt3).start();
- new Thread(mt4).start();
- new Thread(mt5).start();
- }
- }
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class TimeMillis {
- //创建对象时初始化属性t,获取系统时间 要使用同步
- private long t=System.currentTimeMillis();
- private int count=0;
- private Lock lock=new ReentrantLock();
- private Condition con=lock.newCondition();
- private boolean flag;
- private int x=1;
- void getTime() throws InterruptedException{
- lock.lock();
- try{
- while(flag){
- con.await();
- }
- flag=true;
- //线程执行时获取系统时间
- long t1= System.currentTimeMillis();
- //判断线程执行时的系统时间和对象初始化的系统时间差值是否是30的整数倍,是就打印线程名
- if(((t1-t)/30)>=x){
- x++;
- count++;
- System.out.println(t1);
- System.out.println(Thread.currentThread().getName()+"第"+count+"次"+(t1-t));
- }
- flag=false;
- con.signal();
- }finally{
- lock.unlock();
- }
- }
- }
- package test11;
- public class MyThread implements Runnable {
- private TimeMillis tm;
- MyThread(TimeMillis tm){
- this.tm=tm;
- }
- //线程的执行语句
- public void run() {
- int x=0;
- while(x<10000){
- x++;
- try {
- tm.getTime();
- } catch (Exception e) {
- System.out.println("线程异常中断");
- }
- }
- }
- }
复制代码
|
|