Created
January 15, 2014 13:10
-
-
Save reddragon/8435913 to your computer and use it in GitHub Desktop.
Threading Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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