07.03.2014 Views

Programowanie współbieżne w języku Java

Programowanie współbieżne w języku Java

Programowanie współbieżne w języku Java

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Prosty program zawierający dwa wątki (instrukcje niskopoziomowe), działanie mechanizmu<br />

przerwao, wykorzystanie narzędzia Profiler z Netbeans IDE do obserwacji (Sun <strong>Java</strong> tutorial).<br />

public class SimpleThreads {<br />

public static long startTime = 0;<br />

// Display a message, proceed by the name of current thread.<br />

static void threadMessage (String message) {<br />

String threadName = Thread.currentThread().getName();<br />

long time = System.currentTimeMillis() - startTime;<br />

System.out.format("%s: %d: %s%n", threadName, time, message);<br />

}<br />

private static class MessageLoop implements Runnable {<br />

public void run() {<br />

String importantInfo[] = {<br />

"Message no.1", "Message no.2", "Message no.3", "Message no.4"<br />

};<br />

try {<br />

for (int i = 0; i < importantInfo.length; i++) {<br />

Thread.sleep(3500); // Pause for 3.5 seconds<br />

threadMessage(importantInfo[i]);<br />

}<br />

} catch (InterruptedException e) {<br />

threadMessage("I wasn't done!");<br />

}<br />

}<br />

}<br />

public static void main(String[] args) throws InterruptedException {<br />

// delay in miliseconds before we interrupt MessageLoop thread<br />

// default is one hour<br />

long patience = 1000*60*60;<br />

// If command line present gives patience in seconds<br />

if (args.length > 0) {<br />

try {<br />

patience = Long.parseLong(args[0]) * 1000;<br />

} catch (NumberFormatException e) {<br />

System.err.println("Argument must be an integer.");<br />

System.exit(1);<br />

}<br />

}<br />

}<br />

startTime = System.currentTimeMillis();<br />

threadMessage("Starting MessageLoop thread - patience = "+<br />

new Long(patience).toString());<br />

Thread t = new Thread(new MessageLoop(),"myThread");<br />

t.start();<br />

threadMessage("Waiting for MessageLoop thread to finish.");<br />

// loop until MessageLoop thread exits<br />

while (t.isAlive()) {<br />

threadMessage("Still waiting ...");<br />

// wait maximum 1 second for MessageLoop thread to finish<br />

t.join(1000);<br />

if (((System.currentTimeMillis() - startTime) > patience) &&<br />

t.isAlive()) {<br />

threadMessage("Tired of waiting!");<br />

t.interrupt();<br />

t.join(); //Shouldn't be long now -- wait indefinetely<br />

}<br />

}<br />

threadMessage("Finally - the end");<br />

}<br />

Lab. „<strong>Programowanie</strong> <strong>współbieżne</strong> w <strong>języku</strong> <strong>Java</strong>”<br />

2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!