Created
October 14, 2015 06:45
-
-
Save minheq/9ae7f3ad8cc66c9cd088 to your computer and use it in GitHub Desktop.
ThreadDemoSOP
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
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== end loop ===== | |
This is the first line; | |
The second line starts here. | |
===== 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.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantLock; | |
/** | |
* Created by kevinsteppe on 2/10/15. | |
*/ | |
public class ThreadDemoSOP | |
{ | |
public static final int numLoops = 8; | |
private Lock lock = new ReentrantLock(); | |
private String[] words; | |
private int i; | |
private int size; | |
private int num_threads; | |
public ThreadDemoSOP() | |
{ | |
String s = "This is the first line; The second line starts here."; | |
size = 10; | |
num_threads = 2; | |
words = s.split(" "); | |
i = 0; | |
} | |
public void go() throws Exception | |
{ | |
//Run the multithreaded demo a few times | |
for (int foo = 0; foo < numLoops; foo++) | |
{ | |
i = 0; //reset | |
Thread t1 = new Thread(new ThreadDemo(0)); | |
Thread t2 = new Thread(new ThreadDemo(size/num_threads)); | |
t1.start(); | |
t2.start(); | |
t1.join(); t2.join(); //wait for both | |
System.out.println("===== end loop ====="); | |
} | |
} | |
public static void main (String[] args) throws Exception | |
{ | |
ThreadDemoSOP t = new ThreadDemoSOP(); | |
t.go(); | |
} | |
class ThreadDemo implements Runnable | |
{ | |
private int startAt = 0; | |
public ThreadDemo(int startAt) | |
{ | |
this.startAt = startAt; | |
} | |
public void run () | |
{ | |
lock.lock(); | |
for (int j = 0; j < size/num_threads; j++) | |
{ | |
System.out.print(words[startAt + j] + " "); | |
} | |
System.out.println(); | |
lock.unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment