import java.util.Timer; import java.util.TimerTask; /** * Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed. */ public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); } } //To schedule it to go off every second do: timer.schedule(new RemindTask(), seconds*1000, 1*1000);
Thread
.run()
method, which is
the one that will get called to run the thread.public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); //sets the name of this thread to str. } public void run() { for (int i = 0; i < 10; i++) { //print i and the name of this thread. System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } } public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } }
Runnable
interface.run()
method.import java.awt.Graphics; import java.awt.Color; import java.util.*; import java.text.DateFormat; public class Clock extends java.applet.Applet implements Runnable { private Thread clockThread = null; //Applet method public void init() { setBackground(Color.white); } //Applet method public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); //thread starts running } } //A Thread method. public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); //causes paint() to be called try { Thread.sleep(1000); } catch (InterruptedException e){ } } } //An applet method. public void paint(Graphics g) { Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); DateFormat dateFormatter = DateFormat.getTimeInstance(); g.drawString(dateFormatter.format(date), 5, 10); } // overrides Applet's stop method, not Thread's public void stop() { clockThread = null; } }
new
thread is in the "New Thread" state. It
is no running.start()
method
is called. A call to this method results in the creation of an
execution context for the thread and a call to the thread's
run
method. sleep
, wait
, or is blocking on
I/O.run
method must return. An external stop has to be "soft", as in
previous slide.isAlive
method return true if the thread is
in either the Runnable or "not Runnable" states.yield
s, or its run
method exits.put
while the consumer calls
get
. We want every item to be consumed exactly
once.public class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } }
synchronized
keyword means that only one
thread can be accessing that function at a time.wait
method will block until that object
(CubbyHole
) calls notifyAll
. Since it
blocks it means that some other thread must make that call.ThreadGroup
.public class EnumerateTest { public void listCurrentThreads() { ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int numThreads = currentGroup.activeCount(); Thread[] listOfThreads = new Thread[numThreads]; currentGroup.enumerate(listOfThreads); for (int i = 0; i < numThreads; i++) System.out.println("Thread #" + i + " = " + listOfThreads[i].getName()); } }
ThreadGroup
s are:
getMaxPriority
and setMaxPriority
getDaemon
and setDaemon
getName
getParent
and parentOf
toString
This talk available at http://jmvidal.cse.sc.edu/talks/javathreads/
Copyright © 2009 José M. Vidal
.
All rights reserved.
28 May 2002, 08:35AM