List of usage examples for java.lang Thread start
public synchronized void start()
From source file:edu.umn.cs.spatialHadoop.operations.RangeQuery.java
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); final Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();/*from w w w . ja v a 2 s.c om*/ System.exit(1); } if (paths.length >= 2 && !params.checkInputOutput()) { printUsage(); System.exit(1); } if (params.get("rect") == null) { System.err.println("You must provide a query range"); printUsage(); System.exit(1); } final Path inPath = params.getInputPath(); final Path outPath = params.getOutputPath(); final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle()); // All running jobs final Vector<Long> resultsCounts = new Vector<Long>(); Vector<Job> jobs = new Vector<Job>(); Vector<Thread> threads = new Vector<Thread>(); long t1 = System.currentTimeMillis(); for (int i = 0; i < queryRanges.length; i++) { final OperationsParams queryParams = new OperationsParams(params); OperationsParams.setShape(queryParams, "rect", queryRanges[i]); if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) { // Run in local mode final Rectangle queryRange = queryRanges[i]; final Shape shape = queryParams.getShape("shape"); final Path output = outPath == null ? null : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i))); Thread thread = new Thread() { @Override public void run() { FSDataOutputStream outFile = null; final byte[] newLine = System.getProperty("line.separator", "\n").getBytes(); try { ResultCollector<Shape> collector = null; if (output != null) { FileSystem outFS = output.getFileSystem(queryParams); final FSDataOutputStream foutFile = outFile = outFS.create(output); collector = new ResultCollector<Shape>() { final Text tempText = new Text2(); @Override public synchronized void collect(Shape r) { try { tempText.clear(); r.toText(tempText); foutFile.write(tempText.getBytes(), 0, tempText.getLength()); foutFile.write(newLine); } catch (IOException e) { e.printStackTrace(); } } }; } else { outFile = null; } long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams, collector); resultsCounts.add(resultCount); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (outFile != null) outFile.close(); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); threads.add(thread); } else { // Run in MapReduce mode queryParams.setBoolean("background", true); Job job = rangeQueryMapReduce(inPath, outPath, queryParams); jobs.add(job); } } while (!jobs.isEmpty()) { Job firstJob = jobs.firstElement(); firstJob.waitForCompletion(false); if (!firstJob.isSuccessful()) { System.err.println("Error running job " + firstJob); System.err.println("Killing all remaining jobs"); for (int j = 1; j < jobs.size(); j++) jobs.get(j).killJob(); System.exit(1); } Counters counters = firstJob.getCounters(); Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS); resultsCounts.add(outputRecordCounter.getValue()); jobs.remove(0); } while (!threads.isEmpty()) { try { Thread thread = threads.firstElement(); thread.join(); threads.remove(0); } catch (InterruptedException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Results counts: " + resultsCounts); }
From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java
/** * Launch the application.// www . ja v a2s . c o m * * @param args */ public static void main(String[] args) { StartSplashWindow splashWin = null; Thread tr = null; // // Kommandozeilenargumente parsen // try { if (!parseCliOptions(args)) { System.err.println("Error while scanning CLI-Args...."); System.exit(-1); } } catch (Exception ex2) { System.err.println("Error while scanning CLI-Args...."); System.err.println(ex2.getLocalizedMessage()); System.exit(-1); } // // So, hier knnte ich splashen, alle "gefhrlichen" Sachen sind erledigt // splashWin = new StartSplashWindow(); tr = new Thread(splashWin); tr.start(); try { Thread.sleep(500); } catch (InterruptedException ex1) { } // // GUI starten // EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getLookAndFeel()); // Set cross-platform Java L&F (also called "Metal") UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException ex) { System.out.print("fallback to standart look an feel.."); } catch (ClassNotFoundException ex) { System.out.print("fallback to standart look an feel.."); } catch (InstantiationException ex) { System.out.print("fallback to standart look an feel.."); } catch (IllegalAccessException ex) { System.out.print("fallback to standart look an feel.."); } try { // // das Mainobjekt erzeugen // MainCommGUI window = new MainCommGUI(); window.frmMainWindow.setVisible(true); } catch (Exception e) { System.err.println("Exception: " + e.getLocalizedMessage() + "\n"); e.printStackTrace(); } } }); splashWin.terminate(); }
From source file:edu.umn.cs.sthadoop.trajectory.TrajectoryOverlap.java
public static void main(String[] args) throws Exception { // args = new String[8]; // args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife"; // args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result"; // args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory"; // args[3] = "interval:2008-05-01,2008-05-30"; // args[4] = "time:month"; // args[5] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883"; // args[6] = "-overwrite"; // args[7] = "-local";//"-no-local"; final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); final Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();/*from ww w .j a v a 2 s .c om*/ System.exit(1); } if (paths.length >= 2 && !params.checkInputOutput()) { printUsage(); System.exit(1); } if (params.get("traj") == null) { System.err.println("Trajectory query is missing"); printUsage(); System.exit(1); } // Invoke method to compute the trajectory MBR. String rectangle = getTrajectoryRectangle(params.get("traj")); params.set("rect", rectangle); if (params.get("rect") == null) { System.err.println("You must provide a Trajectory Query"); printUsage(); System.exit(1); } if (params.get("interval") == null) { System.err.println("Temporal range missing"); printUsage(); System.exit(1); } TextSerializable inObj = params.getShape("shape"); if (!(inObj instanceof STPoint)) { LOG.error("Shape is not instance of STPoint"); printUsage(); System.exit(1); } // Get spatio-temporal slices. List<Path> STPaths = getIndexedSlices(params); final Path outPath = params.getOutputPath(); final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle()); // All running jobs final Vector<Long> resultsCounts = new Vector<Long>(); Vector<Job> jobs = new Vector<Job>(); Vector<Thread> threads = new Vector<Thread>(); long t1 = System.currentTimeMillis(); for (Path stPath : STPaths) { final Path inPath = stPath; for (int i = 0; i < queryRanges.length; i++) { final OperationsParams queryParams = new OperationsParams(params); OperationsParams.setShape(queryParams, "rect", queryRanges[i]); if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) { // Run in local mode final Rectangle queryRange = queryRanges[i]; final Shape shape = queryParams.getShape("shape"); final Path output = outPath == null ? null : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i))); Thread thread = new Thread() { @Override public void run() { FSDataOutputStream outFile = null; final byte[] newLine = System.getProperty("line.separator", "\n").getBytes(); try { ResultCollector<Shape> collector = null; if (output != null) { FileSystem outFS = output.getFileSystem(queryParams); final FSDataOutputStream foutFile = outFile = outFS.create(output); collector = new ResultCollector<Shape>() { final Text tempText = new Text2(); @Override public synchronized void collect(Shape r) { try { tempText.clear(); r.toText(tempText); foutFile.write(tempText.getBytes(), 0, tempText.getLength()); foutFile.write(newLine); } catch (IOException e) { e.printStackTrace(); } } }; } else { outFile = null; } long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams, collector); resultsCounts.add(resultCount); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (outFile != null) outFile.close(); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); threads.add(thread); } else { // Run in MapReduce mode Path outTempPath = outPath == null ? null : new Path(outPath, String.format("%05d", i) + "-" + inPath.getName()); queryParams.setBoolean("background", true); Job job = rangeQueryMapReduce(inPath, outTempPath, queryParams); jobs.add(job); } } } while (!jobs.isEmpty()) { Job firstJob = jobs.firstElement(); firstJob.waitForCompletion(false); if (!firstJob.isSuccessful()) { System.err.println("Error running job " + firstJob); System.err.println("Killing all remaining jobs"); for (int j = 1; j < jobs.size(); j++) jobs.get(j).killJob(); System.exit(1); } Counters counters = firstJob.getCounters(); Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS); resultsCounts.add(outputRecordCounter.getValue()); jobs.remove(0); } while (!threads.isEmpty()) { try { Thread thread = threads.firstElement(); thread.join(); threads.remove(0); } catch (InterruptedException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("QueryPlan:"); for (Path stPath : STPaths) { System.out.println(stPath.getName()); } System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Results counts: " + resultsCounts); }
From source file:edu.umn.cs.sthadoop.operations.STRangeQuery.java
public static void main(String[] args) throws Exception { // args = new String[7]; // args[0] = "/home/louai/nyc-taxi/yellowIndex"; // args[1] = "/home/louai/nyc-taxi/resultSTRQ"; // args[2] = "shape:edu.umn.cs.sthadoop.core.STPoint"; // args[3] = "rect:-74.98451232910156,35.04014587402344,-73.97936248779295,41.49399566650391"; // args[4] = "interval:2015-01-01,2015-01-02"; // args[5] = "-overwrite"; // args[6] = "-no-local"; // Query for test with output // args = new String[6]; // args[0] = "/home/louai/nyc-taxi/yellowIndex"; // args[1] = "shape:edu.umn.cs.sthadoop.core.STPoint"; // args[2] = "rect:-74.98451232910156,35.04014587402344,-73.97936248779295,41.49399566650391"; // args[3] = "interval:2015-01-01,2015-01-03"; // args[4] = "-overwrite"; // args[5 ] = "-no-local"; final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); final Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();// w w w . j a v a2 s.co m System.exit(1); } if (paths.length >= 2 && !params.checkInputOutput()) { printUsage(); System.exit(1); } if (params.get("rect") == null) { String x1 = "-" + Double.toString(Double.MAX_VALUE); String y1 = "-" + Double.toString(Double.MAX_VALUE); String x2 = Double.toString(Double.MAX_VALUE); String y2 = Double.toString(Double.MAX_VALUE); System.out.println(x1 + "," + y1 + "," + x2 + "," + y2); params.set("rect", x1 + "," + y1 + "," + x2 + "," + y2); // System.err.println("You must provide a query range"); // printUsage(); // System.exit(1); } if (params.get("interval") == null) { System.err.println("Temporal range missing"); printUsage(); System.exit(1); } TextSerializable inObj = params.getShape("shape"); if (!(inObj instanceof STPoint) && !(inObj instanceof STRectangle)) { LOG.error("Shape is not instance of STPoint or STRectangle"); printUsage(); System.exit(1); } // Get spatio-temporal slices. List<Path> STPaths = getIndexedSlices(params); final Path outPath = params.getOutputPath(); final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle()); // All running jobs final Vector<Long> resultsCounts = new Vector<Long>(); Vector<Job> jobs = new Vector<Job>(); Vector<Thread> threads = new Vector<Thread>(); long t1 = System.currentTimeMillis(); for (Path stPath : STPaths) { final Path inPath = stPath; for (int i = 0; i < queryRanges.length; i++) { final OperationsParams queryParams = new OperationsParams(params); OperationsParams.setShape(queryParams, "rect", queryRanges[i]); if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) { // Run in local mode final Rectangle queryRange = queryRanges[i]; final Shape shape = queryParams.getShape("shape"); final Path output = outPath == null ? null : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i))); Thread thread = new Thread() { @Override public void run() { FSDataOutputStream outFile = null; final byte[] newLine = System.getProperty("line.separator", "\n").getBytes(); try { ResultCollector<Shape> collector = null; if (output != null) { FileSystem outFS = output.getFileSystem(queryParams); final FSDataOutputStream foutFile = outFile = outFS.create(output); collector = new ResultCollector<Shape>() { final Text tempText = new Text2(); @Override public synchronized void collect(Shape r) { try { tempText.clear(); r.toText(tempText); foutFile.write(tempText.getBytes(), 0, tempText.getLength()); foutFile.write(newLine); } catch (IOException e) { e.printStackTrace(); } } }; } else { outFile = null; } long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams, collector); resultsCounts.add(resultCount); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { if (outFile != null) outFile.close(); } catch (IOException e) { e.printStackTrace(); } } } }; thread.start(); threads.add(thread); } else { // Run in MapReduce mode Path outTempPath = outPath == null ? null : new Path(outPath, String.format("%05d", i) + "-" + inPath.getName()); queryParams.setBoolean("background", true); Job job = rangeQueryMapReduce(inPath, outTempPath, queryParams); jobs.add(job); } } } while (!jobs.isEmpty()) { Job firstJob = jobs.firstElement(); firstJob.waitForCompletion(false); if (!firstJob.isSuccessful()) { System.err.println("Error running job " + firstJob); System.err.println("Killing all remaining jobs"); for (int j = 1; j < jobs.size(); j++) jobs.get(j).killJob(); System.exit(1); } Counters counters = firstJob.getCounters(); Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS); resultsCounts.add(outputRecordCounter.getValue()); jobs.remove(0); } while (!threads.isEmpty()) { try { Thread thread = threads.firstElement(); thread.join(); threads.remove(0); } catch (InterruptedException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("QueryPlan:"); for (Path stPath : STPaths) { System.out.println(stPath.getName()); } System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Results counts: " + resultsCounts); }
From source file:com.yahoo.ycsb.db.AsyncHBaseClient.java
public static void main(String[] args) { if (args.length != 4) { System.out.println("usage: ahc zkquorum zkpath threadcount operation_count"); System.exit(0);/*from w ww .j av a 2 s . c om*/ } final int keyspace = 10000; //120000000; final String zkQuorum = args[0]; final String zkPath = args[1]; final int threadcount = Integer.parseInt(args[2]); final int opcount = Integer.parseInt(args[3]) / threadcount; Vector<Thread> allthreads = new Vector<Thread>(); for (int i = 0; i < threadcount; i++) { Thread t = new Thread() { public void run() { try { Random random = new Random(); AsyncHBaseClient cli = new AsyncHBaseClient(); Properties props = new Properties(); props.setProperty("columnfamily", "f1"); props.setProperty("zkquorum", zkQuorum); props.setProperty("zkpath", zkPath); props.setProperty("debug", "true"); cli.setProperties(props); cli.init(); HashMap<String, ByteIterator> result = Maps.newHashMap(); long accum = 0; for (int i = 0; i < opcount; i++) { int keynum = random.nextInt(keyspace); String key = "user" + keynum; long st = System.currentTimeMillis(); int rescode; HashMap<String, ByteIterator> hm = Maps.newHashMap(); hm.put("field1", new ByteArrayByteIterator("value1".getBytes("UTF-8"))); hm.put("field2", new ByteArrayByteIterator("value2".getBytes("UTF-8"))); hm.put("field3", new ByteArrayByteIterator("value3".getBytes("UTF-8"))); hm.put("efield", new ByteArrayByteIterator(HBaseClient.EMPTY_ARRAY)); rescode = cli.insert("bench", key, hm); HashSet<String> s = Sets.newHashSet(); s.add("field1"); s.add("field2"); rescode = cli.read("bench", key, s, result); rescode = cli.delete("bench", key); rescode = cli.read("bench", key, s, result); HashSet<String> scanFields = Sets.newHashSet(); scanFields.add("field1"); scanFields.add("field3"); Vector<HashMap<String, ByteIterator>> scanResults = new Vector<HashMap<String, ByteIterator>>(); rescode = cli.scan("bench", "user2", 20, null, scanResults); long en = System.currentTimeMillis(); accum += (en - st); if (rescode != Ok) { System.out.println("Error " + rescode + " for " + key); } if (i % 10 == 0) { System.out.println( i + " operations, average latency: " + (((double) accum) / ((double) i))); } } System.out.println(new ToStringBuilder(cli._client.stats(), ToStringStyle.MULTI_LINE_STYLE) .toString()); } catch (Exception e) { e.printStackTrace(); } } }; allthreads.add(t); } long st = System.currentTimeMillis(); for (Thread t : allthreads) { t.start(); } for (Thread t : allthreads) { try { t.join(); } catch (InterruptedException e) { } } long en = System.currentTimeMillis(); System.out.println("Throughput: " + ((1000.0) * (((double) (opcount * threadcount)) / ((double) (en - st)))) + " ops/sec"); }
From source file:fresto.datastore.titan.TitanEventWriter.java
public static void main(String[] args) throws Exception { if (args.length < 4) { LOGGER.error(/*w w w . j av a2 s .c om*/ "Argumests needed : <streamer url> <storage backend> <storage hostname> <max commit count>"); System.exit(1); } else { STREAMER_URL = args[0]; STORAGE_BACKEND = args[1]; STORAGE_HOSTNAME = args[2]; try { MAX_COMMIT_COUNT = Integer.parseInt(args[3]); } catch (NumberFormatException e) { LOGGER.error("Commit count should be an integer"); } } final ZMQ.Context context = ZMQ.context(1); final FrestoEventQueue frestoEventQueue = new FrestoEventQueue(); final Thread queueMonitorThread = new Thread() { //Logger _LOGGER = Logger.getLogger("writerThread"); @Override public void run() { while (work) { try { LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size()); Thread.sleep(1000); } catch (InterruptedException ie) { } } } }; final Thread writerThread = new Thread() { //Logger _LOGGER = Logger.getLogger("writerThread"); @Override public void run() { //StopWatch _watch = new JavaLogStopWatch(_LOGGER); FrestoStopWatch _watch = new FrestoStopWatch(); FrestoStopWatch _durationWatch = new FrestoStopWatch(); TitanEventWriter eventWriter = new TitanEventWriter(); // Open database eventWriter.openTitanGraph(); ZMQ.Socket puller = context.socket(ZMQ.PULL); //puller.connect("tcp://" + frontHost + ":" + frontPort); puller.connect(STREAMER_URL); //Consume socket data frestoEventQueue.setPullerSocket(puller); frestoEventQueue.start(); int nextCommitCount = 0; int count = 0; long elapsedTime = 0; long duration = 0; _durationWatch.start(); while (work) { // To wait until at least one event in queue if (frestoEventQueue.isEmpty()) { try { Thread.sleep(SLEEP_TIME); continue; } catch (InterruptedException ie) { } } nextCommitCount = frestoEventQueue.size(); for (int i = 0; i < nextCommitCount; i++) { _watch.start(); count++; FrestoEvent frestoEvent = frestoEventQueue.poll(); try { eventWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes); } catch (Exception e) { e.printStackTrace(); } finally { // } elapsedTime += _watch.stop(); duration += _durationWatch.stop(); if (count == MAX_COMMIT_COUNT) { eventWriter.commitGraph(); LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size()); count = 0; elapsedTime = 0; duration = 0; // Stop FOR clause } } eventWriter.commitGraph(); LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size()); count = 0; elapsedTime = 0; duration = 0; } LOGGER.info("Shutting down..."); if (g.isOpen()) { g.commit(); g.shutdown(); } puller.close(); context.term(); LOGGER.info("Good bye."); } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("Interrupt received, killing server"); // To break while clause frestoEventQueue.stopWork(); work = false; try { writerThread.join(); frestoEventQueue.join(); //queueMonitorThread.join(); } catch (InterruptedException e) { } } }); //queueMonitorThread.start(); writerThread.start(); }
From source file:com.lucidtechnics.blackboard.examples.cocothemonkey.CocoTheMonkey.java
public static void main(String[] _args) throws Exception { try {// ww w .java 2 s.c o m final Blackboard blackboard = new Blackboard(); logger.info("Starting Coco The Monkey"); System.out.println("Starting Coco The Monkey"); Thread thread1 = new Thread(new Runnable() { public void run() { synchronized (blackboard) { try { blackboard.wait(); } catch (InterruptedException e) { } } for (int i = 0; i < 100; i++) { Monkey monkey = new Monkey("Coco-1-" + i); Mango mango = new Mango("Coco-2-" + i); Eagle eagle = new Eagle("Coco-3-" + i); Hunter hunter = new Hunter("Coco-5-" + i); blackboard.placeOnBlackboard(eagle); blackboard.placeOnBlackboard(mango); blackboard.placeOnBlackboard(monkey); blackboard.placeOnBlackboard(hunter); } } }); Thread thread2 = new Thread(new Runnable() { public void run() { synchronized (blackboard) { try { blackboard.wait(); } catch (InterruptedException e) { } } for (int i = 0; i < 100; i++) { Monkey monkey = new Monkey("Coco-4-" + i); Mango mango = new Mango("Coco-1-" + i); Eagle eagle = new Eagle("Coco-5-" + i); Hunter hunter = new Hunter("Coco-3-" + i); blackboard.placeOnBlackboard(eagle); blackboard.placeOnBlackboard(mango); blackboard.placeOnBlackboard(monkey); blackboard.placeOnBlackboard(hunter); } } }); Thread thread3 = new Thread(new Runnable() { public void run() { synchronized (blackboard) { try { blackboard.wait(); } catch (InterruptedException e) { } } for (int i = 0; i < 100; i++) { Monkey monkey = new Monkey("Coco-3-" + i); Mango mango = new Mango("Coco-5-" + i); Eagle eagle = new Eagle("Coco-4-" + i); Hunter hunter = new Hunter("Coco-2-" + i); blackboard.placeOnBlackboard(eagle); blackboard.placeOnBlackboard(mango); blackboard.placeOnBlackboard(monkey); blackboard.placeOnBlackboard(hunter); } } }); Thread thread4 = new Thread(new Runnable() { public void run() { synchronized (blackboard) { try { blackboard.wait(); } catch (InterruptedException e) { } } for (int i = 0; i < 100; i++) { Monkey monkey = new Monkey("Coco-2-" + i); Mango mango = new Mango("Coco-3-" + i); Eagle eagle = new Eagle("Coco-1-" + i); Hunter hunter = new Hunter("Coco-4-" + i); blackboard.placeOnBlackboard(eagle); blackboard.placeOnBlackboard(mango); blackboard.placeOnBlackboard(monkey); blackboard.placeOnBlackboard(hunter); } } }); Thread thread5 = new Thread(new Runnable() { public void run() { synchronized (blackboard) { try { blackboard.wait(); } catch (InterruptedException e) { } } for (int i = 0; i < 100; i++) { Monkey monkey = new Monkey("Coco-5-" + i); Mango mango = new Mango("Coco-4-" + i); Eagle eagle = new Eagle("Coco-2-" + i); Hunter hunter = new Hunter("Coco-1-" + i); blackboard.placeOnBlackboard(eagle); blackboard.placeOnBlackboard(mango); blackboard.placeOnBlackboard(monkey); blackboard.placeOnBlackboard(hunter); } } }); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); try { Thread.currentThread().sleep(1000); } catch (Throwable t) { } synchronized (blackboard) { blackboard.notifyAll(); } Object object = new Object(); synchronized (object) { try { object.wait(); } catch (InterruptedException e) { } } } finally { } }
From source file:fresto.datastore.EventLogWriter.java
public static void main(String[] args) throws Exception { if (args.length != 2) { LOGGER.severe("Argumests needed : <frontHost> <frontPort>"); System.exit(1);/* ww w . j a va 2 s .c om*/ } else { frontHost = args[0]; frontPort = args[1]; LOGGER.info("Connecting... " + frontHost + ":" + frontPort + " with SUB"); } final ZMQ.Context context = ZMQ.context(1); final FrestoEventQueue frestoEventQueue = new FrestoEventQueue(); final Thread queueMonitorThread = new Thread() { Logger _LOGGER = Logger.getLogger("logWriteThread"); @Override public void run() { while (work) { try { _LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size()); Thread.sleep(1000); } catch (InterruptedException ie) { } } } }; final Thread logWriteThread = new Thread() { Logger _LOGGER = Logger.getLogger("logWriteThread"); @Override public void run() { //FrestoStopWatch _watch = new FrestoStopWatch(); //FrestoStopWatch _durationWatch = new FrestoStopWatch(); EventLogWriter eventLogWriter = new EventLogWriter(); // Open database //eventLogWriter.openTitanGraph(); ZMQ.Socket receiver = null; //if("pull".equalsIgnoreCase(subOrPull)) { // receiver = context.socket(ZMQ.PULL); // receiver.connect("tcp://" + frontHost + ":" + frontPort); //} else if("sub".equalsIgnoreCase(subOrPull)) { receiver = context.socket(ZMQ.SUB); receiver.connect("tcp://" + frontHost + ":" + frontPort); receiver.subscribe("".getBytes()); //} else { // LOGGER.severe(subOrPull + " is not supported."); // System.exit(1); //} //Consume socket data frestoEventQueue.setPullerSocket(receiver); frestoEventQueue.start(); int waitingEventCount = 0; //int count = 0; //long elapsedTime = 0; //long duration = 0; //_durationWatch.start(); while (work) { // To wait until at least one event in queue if (frestoEventQueue.isEmpty()) { try { //_LOGGER.info("FrestoEventQueue is empty. Waiting " + SLEEP_TIME + "ms..."); Thread.sleep(SLEEP_TIME); continue; } catch (InterruptedException ie) { } } waitingEventCount = frestoEventQueue.size(); for (int i = 0; i < waitingEventCount; i++) { //_watch.start(); //count++; FrestoEvent frestoEvent = frestoEventQueue.poll(); try { eventLogWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes); } catch (Exception e) { e.printStackTrace(); } finally { // } //elapsedTime += _watch.stop(); //duration += _durationWatch.stop(); //if(count == maxCommitCount) { // eventLogWriter.commitGraph(); // _LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size()); // // count = 0; // elapsedTime = 0; // duration = 0; // // Stop FOR clause //} } //eventLogWriter.commitGraph(); _LOGGER.info("Remaining events " + frestoEventQueue.size()); //count = 0; //elapsedTime = 0; //duration = 0; } _LOGGER.info("Shutting down..."); //if(g.isOpen()) { // g.commit(); // g.shutdown(); //} receiver.close(); context.term(); _LOGGER.info("Good bye."); } }; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println(" Interrupt received, killing logger"); // To break while clause frestoEventQueue.stopWork(); work = false; try { logWriteThread.join(); frestoEventQueue.join(); //queueMonitorThread.join(); } catch (InterruptedException e) { // } } }); //queueMonitorThread.start(); logWriteThread.start(); }
From source file:de.uniwue.info6.database.SQLParserTest.java
public static void main(String[] args) throws Exception { String test = "Dies ist ein einfacher Test"; System.out.println(StringTools.forgetOneWord(test)); System.exit(0);/*from ww w. ja va 2 s .c o m*/ // SimpleTupel<String, Integer> test1 = new SimpleTupel<String, Integer>("test1", 1); // SimpleTupel<String, Integer> test2 = new SimpleTupel<String, Integer>("test1", 12); // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>(); // test.add(test1); // System.out.println(test1.equals(test2)); // System.exit(0); final boolean resetDb = true; // Falls nur nach einer bestimmten Aufgabe gesucht wird final Integer exerciseID = 39; final Integer scenarioID = null; final int threadSize = 1; final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>(); final Long[] performance = new Long[] { 0L, 0L }; // ------------------------------------------------ // final ScenarioDao scenarioDao = new ScenarioDao(); final ExerciseDao exerciseDao = new ExerciseDao(); final ExerciseGroupDao groupDao = new ExerciseGroupDao(); final UserDao userDao = new UserDao(); final ArrayList<Thread> threads = new ArrayList<Thread>(); // ------------------------------------------------ // try { ConnectionManager.offline_instance(); if (resetDb) { Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true); Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true); new GenerateData().resetDB(); ConnectionTools.inst().addSomeTestData(); } } catch (Exception e) { e.printStackTrace(); } // ------------------------------------------------ // final List<Scenario> scenarios = scenarioDao.findAll(); try { // ------------------------------------------------ // String userID; for (int i = 2; i < 100; i++) { userID = "user_" + i; User userToInsert = new User(); userToInsert.setId(userID); userToInsert.setIsAdmin(false); userDao.insertNewInstance(userToInsert); } // ------------------------------------------------ // for (int i = 0; i < threadSize; i++) { Thread thread = new Thread() { public void run() { // ------------------------------------------------ // try { Thread.sleep(new Random().nextInt(30)); } catch (InterruptedException e) { e.printStackTrace(); } // ------------------------------------------------ // User user = userDao.getRandom(); Thread.currentThread().setName(user.getId()); System.err.println( "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n"); // ------------------------------------------------ // for (Scenario scenario : scenarios) { if (scenarioID != null && !scenario.getId().equals(scenarioID)) { continue; } System.out.println(StringUtils.repeat("#", 90)); System.out.println("SCENARIO: " + scenario.getId()); // ------------------------------------------------ // for (ExerciseGroup group : groupDao.findByScenario(scenario)) { System.out.println(StringUtils.repeat("#", 90)); System.out.println("GROUP: " + group.getId()); System.out.println(StringUtils.repeat("#", 90)); List<Exercise> exercises = exerciseDao.findByExGroup(group); // ------------------------------------------------ // for (Exercise exercise : exercises) { if (exerciseID != null && !exercise.getId().equals(exerciseID)) { continue; } long startTime = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { String userID = "user_" + new Random().nextInt(100000); User userToInsert = new User(); userToInsert.setId(userID); userToInsert.setIsAdmin(false); userDao.insertNewInstance(userToInsert); user = userDao.getById(userID); List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise); String solution = solutions.get(0).getQuery(); ExerciseController exc = new ExerciseController().init_debug(scenario, exercise, user); exc.setUserString(solution); String fd = exc.getFeedbackList().get(0).getFeedback(); System.out.println("Used Query: " + solution); if (fd.trim().toLowerCase().equals("bestanden")) { System.out.println(exercise.getId() + ": " + fd); } else { System.err.println(exercise.getId() + ": " + fd + "\n"); } System.out.println(StringUtils.repeat("-", 90)); } long elapsedTime = System.currentTimeMillis() - startTime; // if (i > 5) { // try { // equivalenceLock.lock(performance); // performance[0] += elapsedTime; // performance[1]++; // } catch (Exception e) { // } finally { // equivalenceLock.release(performance); // } // } } } } System.err .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped"); } }; thread.start(); threads.add(thread); } for (Thread thread : threads) { thread.join(); } // try { // equivalenceLock.lock(performance); // long elapsedTime = (performance[0] / performance[1]); // System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000)); // } catch (Exception e) { // } finally { // equivalenceLock.release(performance); // } } finally { } }
From source file:ru.apertum.qsystem.client.forms.FAdmin.java
/** * @param args the command line arguments * @throws Exception//from www . jav a 2 s . c o m */ public static void main(String args[]) throws Exception { QLog.initial(args, 3); Locale.setDefault(Locales.getInstance().getLangCurrent()); //? ? , ? final Thread tPager = new Thread(() -> { FAbout.loadVersionSt(); String result = ""; try { final URL url = new URL(PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Java bot"); conn.connect(); final int code = conn.getResponseCode(); if (code == 200) { try (BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf8"))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } } } conn.disconnect(); } catch (Exception e) { System.err.println("Pager not enabled. " + e); return; } final Gson gson = GsonPool.getInstance().borrowGson(); try { final Answer answer = gson.fromJson(result, Answer.class); forPager = answer; if (answer.getData().size() > 0) { forPager.start(); } } catch (Exception e) { System.err.println("Pager not enabled but working. " + e); } finally { GsonPool.getInstance().returnGson(gson); } }); tPager.setDaemon(true); tPager.start(); Uses.startSplash(); // plugins Uses.loadPlugins("./plugins/"); // ?. FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN); Uses.showSplash(); java.awt.EventQueue.invokeLater(() -> { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { System.out.println(info.getName()); /*Metal Nimbus CDE/Motif Windows Windows Classic //GTK+*/ if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } if ("/".equals(File.separator)) { final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10)); final Enumeration<Object> keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { final Object key = keys.nextElement(); final Object value = UIManager.get(key); if (value instanceof FontUIResource) { final FontUIResource orig = (FontUIResource) value; final Font font1 = new Font(f.getFontName(), orig.getStyle(), f.getSize()); UIManager.put(key, new FontUIResource(font1)); } } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } try { form = new FAdmin(); if (forPager != null) { forPager.showData(false); } else { form.panelPager.setVisible(false); } form.setVisible(true); } catch (Exception ex) { QLog.l().logger().error(" ? ?? . ", ex); } finally { Uses.closeSplash(); } }); }