Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Threading Demo
import java.util.Random;
class FooThread extends Thread {
int threadNum;
Random random;
FooThread(int threadNum) {
this.threadNum = threadNum;
this.random = new Random(System.currentTimeMillis() + threadNum);
}
public void run() {
for (int i = 0; i < 5; i++) {
int sleepSeconds = random.nextInt(5);
System.out.printf("Thread #%d, sleeping for %d seconds\n", threadNum,
sleepSeconds);
try {
Thread.sleep(sleepSeconds * 1000);
} catch (InterruptedException ie) {
System.out.println("Thread was interrupted: " + ie);
}
}
System.out.printf("Thread #%d done.\n", threadNum);
}
}
class FooRunnable implements Runnable {
int threadNum;
Random random;
Object lockObject;
FooRunnable(int threadNum, Object lockObject) {
this.threadNum = threadNum;
this.random = new Random(System.currentTimeMillis() + threadNum);
this.lockObject = lockObject;
}
public void run() {
synchronized (lockObject) {
for (int i = 0; i < 5; i++) {
int sleepSeconds = random.nextInt(5);
System.out.printf("Thread #%d, sleeping for %d seconds\n", threadNum,
sleepSeconds);
try {
Thread.sleep(sleepSeconds * 1000);
} catch (InterruptedException ie) {
System.out.println("Thread was interrupted: " + ie);
}
}
}
System.out.printf("Thread #%d done.\n", threadNum);
}
}
public class TestThread {
public static void doSomething(Object lockObject) {
Thread t1 = new Thread(new FooRunnable(3, lockObject));
Thread t2 = new Thread(new FooRunnable(4, lockObject));
t2.start();
t1.start();
// t2.start();
}
public static void main(String[] args) throws InterruptedException {
Integer fooObject = 1, fooObject2 = 2;
doSomething(fooObject);
//FooThread t1 = new FooThread(1);
// FooThread t2 = new FooThread(2);
Thread t1 = new Thread(new FooRunnable(1, fooObject));
Thread t2 = new Thread(new FooRunnable(2, fooObject));
t1.start();
t2.start();
// t1.join();
// t2.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment