multithreading - How can I make this java program run in multi core? -
this program generate possible strings given char sequence given set take time, how can run in multi cpu?
public class laptest { static int q=0; public static void main(string[] args) { system.out.println("first test"); char set1[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; int k = 4; printallklength(set1, k); system.out.println(q); } // method prints possible strings of length k. // wrapper on recursive function printallklengthrec() static void printallklength(char set[], int k) { int n = set.length; printallklengthrec(set, "", n, k); } // main recursive method print possible strings of length k static void printallklengthrec(char set[], string prefix, int n, int k) { // base case: k 0, print prefix if (k == 0) { q++; system.out.println(prefix); if (prefix.equals("hkka")) { system.exit(0); } return; } // 1 one add characters set , recursively // call k equals k-1 (int = 0; < n; ++i) { // next character of input added string newprefix = prefix + set[i]; // k decreased, because have added new character printallklengthrec(set, newprefix, n, k - 1); } } }
your program i/o bound, means writing output screen take more time calculating string. processing in parallel not in way. no matter string later on, on modern computer, sink (consumer of string) slower calculating it, imperfect solution.
also writing string screen, use buffered writer make program faster. define bufferedoutputstream in class:
static bufferedoutputstream out = new bufferedoutputstream(system.out, 81920);
then write out.write((prefix+"\n").getbytes());
, don't forget flush stream out.flush();
on both end of program , on system.exit(0);
. give significant performance improvement.
also try not solve problem without recursion, might give speed pump.
Comments
Post a Comment