public void actionPerformed(ActionEvent ae) { // 响应用户点击 if (ae.getActionCommand().equals("new_game")) { // 如果选择 “开始新游戏” 则跳转到游戏开始 ae_panel = new GamePanel(false); Thread ae_thread = new Thread(ae_panel); ae_thread.start(); // 先删除旧面板 -- 开始界面 this.remove(start_panel); this.add(ae_panel); this.addKeyListener(ae_panel); this.setVisible(true); // 如果没有这句点击后不会出现新的游戏面板 } else if (ae.getActionCommand().equals("qs_game")) { // 退出时保存游戏进度 Recorder.set_enemies(ae_panel.enemies); Recorder.save_game_data(); // 0 表示正常退出 System.exit(0); } else if (ae.getActionCommand().equals("restart_old_game")) { // 恢复游戏数据 -- 如果曾经保存 Recorder.recovery_position(); ae_panel = new GamePanel(true); Thread ae_thread = new Thread(ae_panel); ae_thread.start(); // 先删除旧面板 -- 开始界面 this.remove(start_panel); this.add(ae_panel); this.addKeyListener(ae_panel); this.setVisible(true); } else if (ae.getActionCommand().equals("save_now")) { Recorder.set_enemies(ae_panel.enemies); Recorder.recovery_position(); } }
public static void main(String[] args) { Thread prodThread = new Thread(new Producer(), "Producer"); Thread consThread = new Thread(new Consumer(), "Consumer"); prodThread.start(); consThread.start(); }
public void testEarlySet() throws InterruptedException { final BlockingCell<String> cell = new BlockingCell<String>(); final AtomicReference<String> holder = new AtomicReference<String>(); Thread getterThread = new Thread( new Runnable() { public void run() { try { Thread.sleep(300); holder.set(cell.get()); } catch (InterruptedException ie) { // no special handling required } } }); Thread setterThread = new Thread( new Runnable() { public void run() { cell.set("hello"); } }); getterThread.start(); setterThread.start(); getterThread.join(); setterThread.join(); assertEquals("hello", holder.get()); }
public static void main(String[] args) throws InterruptedException { final Runner runner = new Runner(); Thread thread1 = new Thread( () -> { try { runner.firstThread(); } catch (InterruptedException e) { } }); Thread thread2 = new Thread( () -> { try { runner.secondThread(); } catch (InterruptedException e) { } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); runner.printCount(); }
@Test public void testRunThreads() throws InterruptedException { int numThreads = 2; CountDownLatch latch = new CountDownLatch(numThreads); UpdateTask task1 = new UpdateTask(dao, 1L, latch) { @Override Item editItem(Item item) { item.setProperty2("p2=task1"); return dao.setProperty2(item); } }; UpdateTask task2 = new UpdateTask(dao, 1L, latch) { @Override Item editItem(Item item) { item.setProperty1("p1=task2"); return dao.setProperty1(item); } }; Thread t1 = new Thread(task1); Thread t2 = new Thread(task2); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(task1.result); System.out.println(task2.result); }
// --------------------------------actionConnect------------------------------ private void actionConnect() { if (oParty == null) { JOptionPane.showMessageDialog(frame, "Make a party before trying to connect."); return; } String[] oResults = (String[]) DialogManager.show(DialogManager.CONNECT, frame); if (oResults[DialogManager.RETURN_IP].equals("cancel")) return; lblStatus3.setText("Connecting..."); try { oConn.connect( oResults[DialogManager.RETURN_IP], Integer.parseInt(oResults[DialogManager.RETURN_PORT])); } catch (UnknownHostException e) { JOptionPane.showMessageDialog( frame, "The IP of the host cannot be determined.", "Unknown Host Exception", JOptionPane.ERROR_MESSAGE); frame.repaint(); return; } catch (IOException e) { JOptionPane.showMessageDialog( frame, e.getMessage(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE); frame.repaint(); return; } echo("Connected to opponent!"); tConn = new Thread(oConn, "conn"); tConn.start(); tMain = new Thread(this, "main"); tMain.start(); }
/** * Executes the test. * * @since 1.00 */ private static void execute() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } ThreadedTest listener = new ThreadedTest(); r1 = new Runnable1(listener, 0 /*8 * MILLI_SEC*/); Thread t1 = new Thread(r1); r2 = new Runnable2(listener, 0 /*19 * MILLI_SEC*/); Thread t2 = new Thread(r2); r3 = new Runnable3(listener, 0 /*25 * MILLI_SEC*/); Thread t3 = new Thread(r3); TestEnvironment.notice("Starting runnable 1"); t1.start(); TestEnvironment.notice("Starting runnable 2"); t2.start(); TestEnvironment.notice("Starting runnable 3"); t3.start(); while (finished < 3 || t1.isAlive() || t2.isAlive() || t3.isAlive()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } }
/** * size:2 scenario: pop,pop,push,push,push,push,pop,pop * * @throws InterruptedException */ public void test() throws InterruptedException { BlockingQueue blockingQueue = new BlockingQueueImpl(2); QueueThreadPop queueThreadPop = new QueueThreadPop(blockingQueue, 2); Thread threadPop = new Thread(queueThreadPop); threadPop.start(); Integer expected = new Integer(1); Integer expected2 = new Integer(2); Integer expected3 = new Integer(3); Integer expected4 = new Integer(4); List<Object> expectedList = new ArrayList<Object>(); expectedList.add(expected); expectedList.add(expected2); List<Object> values = new ArrayList<Object>(); values.add(expected); values.add(expected2); values.add(expected3); values.add(expected4); QueueThreadPush queueThread = new QueueThreadPush(blockingQueue, values); Thread thread = new Thread(queueThread); thread.start(); thread.join(); List<Object> result = queueThreadPop.getValues(); assertEquals(expectedList.size(), result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(expectedList.get(i), result.get(i)); } assertEquals(expected3, blockingQueue.pop()); assertEquals(expected4, blockingQueue.pop()); }
public static void main(String[] args) { Thread thread = new Thread( new Runnable() { @Override public void run() { try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } }, "rookiefly"); /* try { Thread.sleep(1 * 60 * 1000); } catch (InterruptedException e) { e.printStackTrace(); }*/ thread.start(); try { thread.join(); thread.start(); } catch (InterruptedException e) { e.printStackTrace(); } BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in); try { bufferedInputStream.read(); } catch (IOException e) { e.printStackTrace(); } }
public void main() { System.out.println("Starting ..."); long start = System.currentTimeMillis(); Thread t1 = new Thread( new Runnable() { public void run() { process(); } }); Thread t2 = new Thread( new Runnable() { public void run() { process(); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("Time taken: " + (end - start)); System.out.println("List1: " + list1.size() + "; List2: " + list2.size()); }
@Override public boolean onContextItemSelected(MenuItem item) { // 擷取是哪個位置的Item被select AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final int ItemPosition = info.position; switch (item.getItemId()) { case 0: CheckChangeNumberState CCNS = new CheckChangeNumberState(); CCNS.setdata(ItemPosition); Thread CheckChangeNumberStateThread = new Thread(CCNS); CheckChangeNumberStateThread.start(); break; case 1: ImplementChangeNumber ICN = new ImplementChangeNumber(); ICN.setData(1, ItemPosition); Thread ICNThread = new Thread(ICN); ICNThread.start(); break; case 2: AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("換號確認"); builder.setMessage("你確定要換號?"); builder.setPositiveButton( "確認", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ImplementChangeNumber ICN = new ImplementChangeNumber(); ICN.setData(2, ItemPosition); Thread ICNThread = new Thread(ICN); ICNThread.start(); } }); builder.setNegativeButton( "取消", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); AlertDialog alert = builder.create(); alert.show(); break; case 3: GetMyItem GMI = new GetMyItem(ItemPosition); Thread GMIThread = new Thread(GMI); GMIThread.start(); break; case 4: new DeleteItem().execute(ItemPosition); break; } return super.onContextItemSelected(item); }
public void test() { Thread thread1 = new Thread() { public void run() { UnitOfWork uow = getSession().acquireUnitOfWork(); cloned = (ConcurrentPerson) uow.registerObject(person); } }; Thread thread2 = new Thread() { public void run() { getSession().refreshObject(person.address); } }; thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (Exception ex) { // just an inturrupt ignore } ConcurrentAddress.RUNNING_TEST = ConcurrentAddress.NONE; if (!(cloned.getAddress().getStreet().equals("Start") && cloned.getAddress().getPostalCode().equals("H0H0H0"))) { if (!(cloned.getAddress().getStreet().equals("Corrupted") && cloned.getAddress().getPostalCode().equals("A1A1A1"))) { throw new TestErrorException("Failed to wholly clone the object"); } else { getSession().logMessage("LockOnCloneTest :-> Clone blocked on Refresh"); } } else { getSession().logMessage(" LockOnCloneTest :-> refresh blocked on clone"); } }
public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread( new Runnable() { @Override public void run() { try { producer(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread( new Runnable() { @Override public void run() { try { consumer(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t1.join(); t2.join(); }
public static void main(String[] args) { System.out.println("Test"); // while (true) { // } // MyTaskThread taskThread = new MyTaskThread(); // taskThread.start(); // MyTaskThread taskThread1 = new MyTaskThread(); // taskThread1.start(); // MyTaskThread taskThread3 = new MyTaskThread(); // taskThread3.start(); // System.out.println("End of job"); // // System.out.println("----------------------------"); // Thread thread = new Thread((new MyTaskRunnible())); // Thread thread1 = new Thread((new MyTaskRunnible())); // Thread thread2 = new Thread((new MyTaskRunnible())); // // thread.start(); // thread1.start(); // thread2.start(); Thread timer1 = new Thread(new MyTimer(10, "First timer")); Thread timer2 = new Thread(new MyTimer(20, "Second timer")); Thread timer3 = new Thread(new MyTimer(30, "Third timer")); timer1.start(); timer2.start(); timer3.start(); System.out.println("Main thread is over"); }
public static void main(String[] args) { final StoreBufferExample sbe1 = new StoreBufferExample(); // Seems necessary to call threadA and threadB many times to make // sure they are compiled (JITted) to machine code: for (int i = 0; i < 100000; i++) { sbe1.threadA(); sbe1.threadB(); } final StoreBufferExample sbe2 = new StoreBufferExample(); Thread tA = new Thread( new Runnable() { public void run() { sbe2.threadA(); } }), tB = new Thread( new Runnable() { public void run() { sbe2.threadB(); } }); tA.start(); tB.start(); }
@BeforeClass public static void setUpOnce() throws IOException { proxyServer = new Thread( new Runnable() { public void run() { main.runMain(args); } }); proxyServer.start(); webServer = new Thread( new Runnable() { public void run() { try { serverSocket = new ServerSocket(9001); while (true) { final Socket socket = serverSocket.accept(); new Thread(new PersistentStaticHttpServer(socket, CONTENT)).start(); } } catch (IOException e) { // throw new RuntimeException(e); } } }); webServer.start(); }
public static void test() { Thread thread1 = new Thread(new ExtendThread(), "thread1"); Thread thread2 = new Thread(new ExtendThread(), "thread2"); // The below 2 threads are assigned default names Thread thread3 = new ExtendThread(); Thread thread4 = new ExtendThread(); Thread thread5 = new ExtendThread("thread5"); // Start the threads thread1.start(); thread2.start(); /** * start() Causes this thread to begin execution; the Java Virtual Machine calls the run method * of this thread. IllegalThreadStateException is thrown if try to start the same thread again */ // Display info about the main thread,since the exectuion is taking place in the main thread System.out.println("Current thread where sysout is provided-" + Thread.currentThread()); thread3.start(); thread4.start(); try { // The sleep() method is invoked on the main thread to cause a one second delay. Thread.sleep(1000); } catch (InterruptedException e) { } // thread1.start(); //IllegalThreadStateException }
/** * Entry point into the program that creates two instances of SimpleQueue (aQueue and bQueue) and * two Threads that attempt to transfer the contents of aQueue and bQueue in opposite orders. * Although this will work sometimes, it also often deadlocks since the Deadlock.transfer() method * running in one Thread will acquire aQueue's monitor lock, while the Deadlock.transfer() method * running in another Thread will acquire bQueue's monitor lock. At this point, both Threads are * waiting to acquire the other SimpleQueue's monitor lock, which causes a circular wait that * doesn't terminate! */ public static void main(String[] args) { // Designated the number of iterations to run in each thread. int iterations = args.length > 0 ? Integer.parseInt(args[0]) : 1000000; // Create two SimpleQueue's. final SimpleQueue<String> aQueue = new SimpleQueue<String>(); final SimpleQueue<String> bQueue = new SimpleQueue<String>(); // Create/start a Thread that transfers the contents of aQueue // to bQueue. Thread transfer1 = new Thread(new TransferRunnable(aQueue, bQueue, iterations)); // Create/start a Thread that transfers the contents of bQueue // to aQueue, which is the reverse of what Thread t1 does (and // thus can lead to deadlock). Thread transfer2 = new Thread(new TransferRunnable(bQueue, aQueue, iterations)); System.out.println("starting first transfer thread"); transfer1.start(); System.out.println("starting second transfer thread"); transfer2.start(); try { transfer1.join(); System.out.println("joined first transfer thread"); transfer2.join(); System.out.println("joined second transfer thread"); } catch (Exception e) { System.out.println("caught exception"); } }
private void checkBoxMouseClicked(MouseEvent event, int index) { CheckBox cb = checkBoxArray[index]; int y = (int) cb.getLayoutY() + radius; if (cb.isSelected() && index < 5) { // Reader selected Ball b = new Ball(minX, maxX, minCsX, maxCsX, y, balColor1, "reader"); ballArray[index] = b; Thread t = new Thread(new BallRunnable(b, readWrite)); threadArray[index] = t; circleArray[index].setVisible(true); t.start(); } else if (cb.isSelected() && index >= 5) { // Writer selected Ball b = new Ball(minX, maxX, minCsX, maxCsX, y, balColor2, "writer"); ballArray[index] = b; Thread t = new Thread(new BallRunnable(b, readWrite)); threadArray[index] = t; circleArray[index].setVisible(true); t.start(); } else { threadArray[index].interrupt(); threadArray[index] = null; ballArray[index] = null; circleArray[index].setVisible(false); circleArray[index].setCenterX(minX); } }
public static void main(String[] args) { Thread t1 = new Thread() { @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println(getName() + "..aaa"); } } }; Thread t2 = new Thread() { @Override public void run() { for (int i = 0; i < 50; i++) { if (i == 2) { try { t1.join(10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName() + "...bbb"); } } }; t1.start(); t2.start(); }
@Test public void testRootsHolder() throws InterruptedException { GroupID[] groupIds = new GroupID[NUM_GROUPS]; for (int i = 0; i < NUM_GROUPS; i++) { groupIds[i] = new GroupID(i); } RootsHolder rootsHolder = new RootsHolder(groupIds); Thread tAlpha = new Thread(new RootsHolderTestRunnable(rootsHolder, barrier, 0, assertErrorMarker)); Thread tBeta = new Thread( new RootsHolderTestRunnable( rootsHolder, barrier, NUM_GROUPS * INSERTIONS_PER_GROUP, assertErrorMarker)); tAlpha.start(); tBeta.start(); tAlpha.join(); tBeta.join(); assertNull(assertErrorMarker.get()); assertEquals( rootsHolder.getGroupIDForRoot(NAME_ZERO), rootsHolder.getGroupIDForRoot(NAME_ZERO)); assertEquals(new ObjectID(1), rootsHolder.getRootIDForName(NAME_ZERO, GID_ZERO)); }
@Test public void testInstanceRaceNoThrow() { if (verifyPropertyViolation(PROPERTY, LISTENER)) { final SharedObject o = new SharedObject(); Runnable r1 = new Runnable() { SharedObject d = o; public void run() { d.instanceField = 1; } }; Runnable r2 = new Runnable() { SharedObject d = o; public void run() { d.instanceField = 0; } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
// ----------------------------------------// public static void main(String[] args) { Vector trabajos = new Vector(); Thread masterT = new Thread(new Master(trabajos)); Thread workerT = new Thread(new Worker(trabajos)); masterT.start(); workerT.start(); }
@Test public void testArrayRaceNoThrow() { if (verifyPropertyViolation(PROPERTY, LISTENER, "+cg.threads.break_arrays")) { final int[] shared = new int[1]; Runnable r1 = new Runnable() { int[] a = shared; public void run() { a[0] = 0; } }; Runnable r2 = new Runnable() { int[] a = shared; public void run() { a[0] = 1; } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
@Test public void test() { Cinema cinema = new Cinema(); System.out.println( "Begin ticket number:" + cinema.getVacanciesCinema1() + ", " + cinema.getVacanciesCinema2()); Thread ticketOffice1 = new Thread(new TicketOffice1(cinema)); Thread ticketOffice2 = new Thread(new TicketOffice2(cinema)); ticketOffice1.start(); ticketOffice2.start(); try { ticketOffice1.join(); ticketOffice2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println( "Finished ticket number:" + cinema.getVacanciesCinema1() + ", " + cinema.getVacanciesCinema2()); }
@Test public void testNoArrayRaceElements() { if (verifyNoPropertyViolation(LISTENER, "+cg.threads.break_arrays")) { final int[] shared = new int[2]; Runnable r1 = new Runnable() { int[] a = shared; public void run() { a[0] = 0; } }; Runnable r2 = new Runnable() { int[] a = shared; public void run() { a[1] = 1; } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
@Test public void testProxy() throws Exception { int frontendPort = Utils.findOpenPort(); int backendPort = Utils.findOpenPort(); Context ctx = ZMQ.context(1); assert (ctx != null); Main mt = new Main(ctx, frontendPort, backendPort); mt.start(); new Dealer(ctx, "AA", backendPort).start(); new Dealer(ctx, "BB", backendPort).start(); Thread.sleep(1000); Thread c1 = new Client(ctx, "X", frontendPort); c1.start(); Thread c2 = new Client(ctx, "Y", frontendPort); c2.start(); c1.join(); c2.join(); ctx.term(); }
@Test public void testStaticRace() { if (verifyUnhandledException("java.lang.RuntimeException")) { Runnable r1 = new Runnable() { public void run() { staticField = 1; if (staticField != 1) { throw new RuntimeException("r1 detected race!"); } } }; Runnable r2 = new Runnable() { public void run() { staticField = 0; if (staticField != 0) { throw new RuntimeException("r2 detected race!"); } } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
@Test public void testStaticRaceNoThrow() { if (verifyPropertyViolation(PROPERTY, LISTENER)) { Runnable r1 = new Runnable() { public void run() { staticField = 1; } }; Runnable r2 = new Runnable() { public void run() { staticField = 0; } }; Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }
/** * Spawn the application * * @throws IOException IO problems * @throws SliderException internal state of this class is wrong */ public void spawnApplication() throws IOException, SliderException { execThread = spawnIntoThread(); execThread.start(); processStreamReader = new ProcessStreamReader(processLog, STREAM_READER_SLEEP_TIME); logThread = new Thread(processStreamReader, "IO"); logThread.start(); }