java 之父的小故事_Java之父22年前写的一段代码

[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");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值