//thread examples from Schildt public class TestThreads2 { public static void main (String[] args) { Thread me = Thread.currentThread(); me.setName("I'm main thread"); me.setPriority(Thread.MAX_PRIORITY); System.out.print("thread ref: "+me); System.out.println(" isAlive: "+me.isAlive()); /* MyRunnable r1 = new MyRunnable(Thread.MIN_PRIORITY); MyRunnable r2 = new MyRunnable(Thread.MAX_PRIORITY); r1.start(); r2.start(); */ /* try { Thread.sleep(10000); } catch (InterruptedException e) {} r1.stop(); r2.stop(); */ //ctor with 0 args: //new MyRunnable(); //ctor with float arg: instantiates thread and starts it new MyRunnable(3.1415f); /* try { r1.t.join(); r2.t.join(); } catch (InterruptedException e) {} */ System.out.println("main quitting"); } } class MyRunnable implements Runnable { Thread t; int click; private int mutex; private boolean running = true; MyRunnable() { t = new Thread(this); System.out.println("in ctor: "+t); t.start(); } MyRunnable(int p) { //runnable needs to call its start t = new Thread(this); System.out.println("in int ctor: "+t); } MyRunnable(float dummy) { new Thread(this).start(); System.out.println("in float ctor: "); } public void run() { System.out.println("in run: this: "+this+" thread t: "+t); /* while (running) { for (int i=0; i<1000000; i++) ; click++; } System.out.println("thread t: "+t+" clicks: "+click); */ synchmethod(); } public void stop() { running = false; } public void start() { //method of Myrunnable t.start(); //overridden Thread method } synchronized void synchmethod() { System.out.println(t+" in synch method"); mutex++; try { Thread.sleep(3000); } catch (InterruptedException e) {} System.out.println(t+" leaving synch method: mutex="+mutex); } }