Здравейте,
Бих се радвал да коментирате следния пример за управкление на нишки с монитори. Как го намирате? Дали е достатъчно добър или не ви харесва нещо в него? Приемам всякакви критики и предварително благодаря.
public class Start {
static class MyTask implements Runnable
{
static final long STEP = 1000000;
static final long COUNT = 100000000;
String whoIsTheBest = "I don't know. :(";
public void run() {
// get the key of current object
synchronized (this) {
this.whoIsTheBest = "Me of cource! ;)";
for (int i = 0; i < COUNT; i++) {
if ( (i % STEP) == 0 ){
System.out.print("*");
}
}
// notify the thread that is waiting for this key
this.notify();
}
}
public String getWhoIsTheBest()
{
return this.whoIsTheBest;
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args){
System.out.println("Hello!");
MyTask task = new MyTask();
System.out.println(task.getWhoIsTheBest());
// start the new thread
new Thread(task).start();
// sleep the current thread so the new thread can start executing
try {
Thread.sleep(5);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
// wait the new thread to release its key
synchronized (task) {
try {
Thread.currentThread().wait();
} catch (Exception e) {}
}
System.out.println("\n" + task.getWhoIsTheBest());
System.out.println("\nBye!");
}
}