[Listing One]PingPong class PingPong extends Thread { String word; // what word to print int delay; // how long to pause
PingPong(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; } public void run() { try { for (;;) { System.out.print(word + " "); sleep(delay); // wait until next time } } catch (InterruptedException e) { return; // end this thread } } public static void main(String[] args) { new PingPong("ping", 33).start(); // 1/30 second new PingPong("PONG", 100).start(); // 1/10 second }
}
[Listing Two]
Account class Account {
private double balance;public Account(double initialDeposit) { balance = initialDeposit; } public synchronized double getBalance() { return balance; } public synchronized void deposit(double amount) { balance += amount; }
}
[Listing Three]
synchronized_abs /* make all elements in the array nonnegative /
public static void abs(int[] values) {
synchronized (values) {
for (int i = 0; i < values.length; i++) {
if (values[i] < 0)
values[i] = -values[i];
}
}
}[Listing Four]
class Queue {
// The first and last elements in the queue
Element head, tail;public synchronized void append(Element p) { if (tail == null) head = p; else tail.next = p; p.next = null; tail = p; notify(); // Let waiters know something arrived } public synchronized Element get() { try { while(head == null) wait(); // Wait for an element } catch (InterruptedException e) { return null; } Element p = head; // Remember first element head = head.next; // Remove it from the queue if (head == null) // Check for an empty queue tail = null; return p; }
}
[Listing Five]
Thread spinner; // the thread doing the processing
public void userHitCancel() {
spinner.suspend(); // whoa!
if (askYesNo("Really Cancel?"))
spinner.stop(); // stop it
else
spinner.resume(); // giddyap!
}[Listing Six]
class CalcThread extends Thread {
private double Result;public void run() { Result = calculate(); } public double result() { return Result; } public double calculate() { // ... }
}
class Join {
public static void main(String[] args) {
CalcThread calc = new CalcThread();
calc.start();
doSomethingElse();
try {
calc.join();
System.out.println("result is "+ calc.result()); } catch (InterruptedException e) { System.out.println("No answer: interrupted"); } }
}
学编程,从w3cschool开始,w3cschool推出的编程微课,采用游戏化的编程闯关模式,让你快速掌握编程这一门手艺。微课学习入口:W3Cschool编程微课
声明:小猿资源站是一个资源分享和技术交流平台,本站所发布的一切破解补丁、注册机和注册信息及软件的解密分析文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。