Last active
October 14, 2015 06:51
-
-
Save minheq/21a50f12705cd10313d5 to your computer and use it in GitHub Desktop.
AA Ex
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
Hello World | |
Hello World | |
Hello World | |
Hello World | |
Hello World | |
Hello World | |
Hello World | |
Hello World | |
Hello World | |
java.lang.Exception: An exception! | |
at aa.race.ThreadDemo.run(ThreadDemoExc.java:49) | |
at java.lang.Thread.run(Unknown Source) | |
Hello World | |
Hello World | |
Hello World | |
java.lang.Exception: An exception! | |
at aa.race.ThreadDemo.run(ThreadDemoExc.java:49) | |
at java.lang.Thread.run(Unknown Source) | |
===== end loop ===== |
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
package aa.race; | |
import java.util.Random; | |
import java.util.concurrent.locks.*; | |
/** | |
* Created by kevinsteppe on 2/10/15. | |
*/ | |
public class ThreadDemoExc | |
{ | |
public static final int numLoops = 8; | |
private static int num_threads = 4; | |
private static Lock lock = new ReentrantLock(); | |
public static void main(String[] args) throws Exception | |
{ | |
Thread t1 = new Thread(new ThreadDemo(0, lock)); | |
Thread t2 = new Thread(new ThreadDemo(1, lock)); | |
t1.start(); | |
t2.start(); | |
t1.join(); | |
t2.join(); //wait for both | |
System.out.println("===== end loop ====="); | |
} | |
} | |
class ThreadDemo implements Runnable | |
{ | |
int id; | |
Random random = new Random(); | |
Lock lock; | |
public ThreadDemo(int i, Lock lock) | |
{ | |
id = i; | |
this.lock = lock; | |
} | |
public void run() | |
{ | |
lock.lock(); | |
try | |
{ | |
for (int i = 0; i < 10; i++) | |
{ | |
System.out.println("Hello World"); | |
Thread.yield(); | |
int x = random.nextInt(4); | |
if (x == id) | |
throw new Exception("An exception!"); | |
} | |
} catch (Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
lock.unlock(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment