class myclass { static public void main(String args[]) { print_a_file(); manipulate_another_file(); access_database(); draw_picture_on_screen(); } } |
import java.util.*; class TimePrinter extends Thread { 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[]) { TimePrinter tp1 = new TimePrinter(1000, "Fast Guy"); tp1.start(); TimePrinter tp2 = new TimePrinter(3000, "Slow Guy"); tp2.start(); } } |
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 类继承会强加类层次。
到目前为止,我们看到的示例都只是以非常简单的方式来利用线程。只有最小的数据流,而且不会出现两个线程访问同一个对象的情况。但是,在大多数有用的程序中,线程之间通常有信息流。试考虑一个金融应用程序,它有一个 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; } } |
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; } } |