Java threads.



public class MyThread extends Thread {
	
	private String name;
	private long startTime;
	private boolean stop;
	private int counter;
	
	public MyThread(String name) {
		this.name = name;
		startTime = System.currentTimeMillis();
	}
	
	
	public synchronized int incrementCounter() {
		int current = counter;
		counter++;
		return current;
	}
	
	public void run() {		
		while(!stop) {
			// keep running 
		}
	}
	
	public void print() {
		System.out.println("My name is " + name + ", my counter is " + counter + "my stop is " + stop);
		long now = System.currentTimeMillis();
		System.out.println("I've been running for " + (now - startTime) + " milliseconds");
	}
	
	public void stopThread() {
		stop = true;
	}
}



public class ThreadsDemo {

	public static void main(String[] args) {
		MyThread thread1 = new MyThread("One");
		thread1.start();
		MyThread thread2 = new MyThread("Two");
		thread2.start();

		System.out.println(thread1.getState());
		System.out.println(thread2.getState());

		thread1.incrementCounter();
		thread2.incrementCounter();

		System.out.println(thread1.getState());
		System.out.println(thread2.getState());

		System.out.println(thread1.isAlive());
		System.out.println(thread2.isAlive());

		thread1.print();
		thread2.print();

		thread1.stopThread();

		// sleep the current thread
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(thread1.getState());
		System.out.println(thread2.getState());

		thread1.stopThread();

		System.out.println(thread1.isAlive());
		System.out.println(thread2.isAlive());

		// sleep the current thread
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println(thread1.getState());
		System.out.println(thread2.getState());

		thread2.stopThread();

		System.out.println(thread1.isAlive());
		System.out.println(thread2.isAlive());

		thread1.print();
		thread2.print();
	

		System.out.println("both threads are done");

		MyThread[] threads = new MyThread[100];
		for (int i = 0; i < 100; ++i) {
			threads[i] = new MyThread(new Integer(i).toString());
			threads[i].start();
		}

		for (MyThread thread : threads) {
			thread.incrementCounter();
			thread.print();
		}

		for (MyThread thread : threads) {
			System.out.println(thread.getState());
		}

		for (MyThread thread : threads) {
			thread.stopThread();
		}

		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		for (MyThread thread : threads) {
			System.out.println(thread.getState());
		}


		try {
			for (MyThread thread : threads) {

				thread.join();

			}
			System.out.println("All threads done");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


CSci 4651 course web site.