Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 25 Jan, 22:19:36

import java.util.concurrent.atomic.AtomicInteger;

class Task implements Runnable {

private static AtomicInteger count = new AtomicInteger(); 

@Override
public void run() {
	for (int i = 0; i < 10; i++) {
		System.out.println("Thread " + Thread.currentThread().getName() + 
			" is running iteration: " + count.incrementAndGet()); 
		try {
			Thread.sleep(100); 
		}
		catch (InterruptedException e) {
			System.out.println("Thread interrupted"); 
		}
	}
	System.out.println("Thread " + Thread.currentThread().getName() + 
		" Finished");  
}  }

public class ThreadExample { public static void main(String[] args) { Thread t1 = new Thread(new Task()); Thread t2 = new Thread(new Task()); t1.start(); t2.start();

	try {
		t1.join();
		t2.join();
	}
	catch (InterruptedException e) {
		System.out.println("Thread interrupted");
	}
	
	System.out.println("Finished with both threads"); 
}  }