Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Thread counter
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static synchronized void main(String args[]) { System.out.println("Hello, World!"); CounterImpl c = new CounterImpl(); System.out.println(c.get()); c.inc(); System.out.println(c.get()); c.inc(); c.inc(); System.out.println(c.get()); RunTest t0 = RunTest.getThread("0", c, Thread.MIN_PRIORITY); RunTest t1 = RunTest.getThread("1", c, Thread.MAX_PRIORITY); RunTest t2 = RunTest.getThread("2", c, Thread.NORM_PRIORITY); t1.sleeped(1000); try{ //c.notifyAll(); t0.join(); t1.join(); t2.join(); }catch(InterruptedException e){ System.out.println(e); } } } class RunTest extends Thread{ private CounterImpl _counter; private String _name; private boolean _sleep; private int _sleepDuration; public void run(){ test(); } private void test(){ for(int i=0; i<50; i++){ _counter.inc(); System.out.println(String.format("Thread: %s iteration: %s counter: %s", _name, i, _counter.get())); if(_sleep){ _sleep = false; try{ System.out.println(String.format("Thread: %s sleeped by %s ...", _name, _sleepDuration)); Thread.sleep(_sleepDuration); System.out.println(String.format("Thread: %s weakup ...", _name)); }catch(InterruptedException e){ System.out.println(e); } } } System.out.println(String.format("Thread: %s is end!", _name)); } public void sleeped(int duration){ _sleep = true; _sleepDuration = duration; } public static RunTest getThread(String name, CounterImpl counter, int priority){ RunTest th = new RunTest(name, counter); th.setPriority(priority); th.start(); return th; } public static RunTest getThread(String name, int priority){ return getThread(name, null, priority); } private RunTest(String name, CounterImpl counter){ _name = name; _counter = counter; } } class CounterImpl implements Counter{ private static int _counter; public synchronized int get(){return _counter;} public synchronized void inc(){_counter++;} CounterImpl(int startValue){ _counter = startValue; } CounterImpl(){ } } interface Counter{ public int get(); public void inc(); }
run
|
edit
|
history
|
help
0
classwork
jb11.0 threads tick tock 1.0
Day
Java # Dizi ile ek bulma
Implementation of several common methods of LinkedList
Game developer
Armstrong no
preincrement1
has a
Black Jack by Craig