Java写的一个定时器,多线程:
1/* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6package javaapplication1; 7 8import static java.lang.Thread.sleep; 9import java.nio.ByteBuffer; 10import java.text.ParseException; 11import java.text.SimpleDateFormat; 12import java.util.Calendar; 13import java.util.Date; 14import java.util.HashMap; 15import java.util.concurrent.atomic.AtomicBoolean; 16import java.util.logging.Level; 17import java.util.logging.Logger; 18 19/** 20 * 21 * @author Qyee 22 */ 23public class JavaApplication1 { 24 private static final Object lock = new Object(); 25 private static Thread execTrhead; 26 private static AtomicBoolean bRunning = new AtomicBoolean(false); 27 28 /** 29 * @param args the command line arguments 30 */ 31 public static void main(String[] args) throws ParseException, InterruptedException { 32 // TODO code application logic here 33 34 execTrhead = new Thread(new Runnable() { 35 public void run() { 36 do { 37 bRunning.set(true); 38 System.out.println("doing 1"); 39 synchronized (lock) { 40 try { 41 lock.wait(1000); 42 } catch (InterruptedException ex) { 43 Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex); 44 } 45 } 46 System.out.println("doing 2"); 47 } while (bRunning.get()); 48 } 49 }); 50 execTrhead.start(); 51 52 while (true) { 53 System.out.println("notify"); 54 sleep(2000); 55 synchronized (lock) { 56 lock.notify(); 57 } 58 } 59 } 60}