????Runnable ???
????????????????????run()????????????????????????????????????????????????????????????????в????????????? runnable ????д????????????????????ú?????????
???????????????????????????
import java.util.*;
class TimePrinter implements Runnable {
int pauseTime;
String name;
public TimePrinter(int x?? String n) {
pauseTime = x;
name = n;
}
public void run() {
while(true) {
try {
System.out.println(name + ":" + new Date(System.currentTimeMillis()));
Thread.sleep(pauseTime);
} catch(Exception e) {
System.out.println(e);
}
}
}
static public void main(String args[]) {
Thread t1 = new Thread(new TimePrinter(1000?? "Fast Guy"));
t1.start();
Thread t2 = new Thread(new TimePrinter(3000?? "Slow Guy"));
t2.start();
}
}
?????????????? runnable ????????????????????????????????????????? Thread ????????????????????????????????? runnable ????????? Thread ???л???????Ρ?
????synchronized ?????
????????????????????????????????????????????????????С????????????????????????????????????????????????????????????????У?????????????????????????????????ó?????????? Account ?????????????????
????????????е?????
public class Account {
String holderName;
float amount;
public Account(String name?? float amt) {
holderName = name;
amount = amt;
}
public void deposit(float amt) {
amount += amt;
}
public void withdraw(float amt) {
amount -= amt;
}
public float checkBalance() {
return amount;
}
}
??????????????????????????????????????????????ó??????????κ??????????????????ó????????У??????????п????????????? Account ????????????????????????????????? ATM ???????з??????????????£????????????????????????????????????????????????????????????????????????Java ?????????????????????????????????????????????????????????????????????????????????????????? synchronized ????á?????????????? Account ????????????????????????????????????????
??????????????е????????????????
public class Account {
String holderName;
float amount;
public Account(String name?? float amt) {
holderName = name;
amount = amt;
}
public synchronized void deposit(float amt) {
amount += amt;
}
public synchronized void withdraw(float amt) {
amount -= amt;
}
public float checkBalance() {
return amount;
}
}
????deposit() ?? withdraw() ???????????????????в?????????????????????????????????????????????? checkBalance() δ???????????????????????????? checkBalance() δ???????????????κ???????????????????????????????????κ?????????????????Щ????????????????????