java 线程在开发中的应用
Java平台从开始就被设计成为多线程环境。在你的主程序执行的时候,其它作业如碎片收集和事件处理则是在后台进行的。
本质上,你可以认为这些作业是线程。它们正好是系统管理线程,但是无论如何,它们是线程。线程使你能够定义相互独立的作业,彼此之间互不干扰。系统将交换这些作业进或出cpu,这样(从外部看来)它们好象是同时运行的。
在你需要在你的程序中处理多个作业时,你也可以使用多个进程。这些进程可以是你自己创建的,你也可以操纵系统线程。你进行这些多作业处理,要使用几个不同的类或接口:
◆java.util.timer类
◆javax.swing.timer类
◆thread类
◆runnable接口
对于简单的作业,通常需要重复的,你可以使用java.util.timer类告诉它“每半秒钟做一次”。注意:大多数系统例程是使用毫秒的。半秒钟是500毫秒。
你希望timer实现的任务是在java.util.timertask实例中定义的,其中运行的方法包含要执行的任务。这些在hi类中进行了演示,其中字符串“hi”重复地被显示在屏幕上,直到你按enter键。
import java.util.*;public class hi{public static void main(string args);timer.cancel();}}
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class count{public static voidmain(string args){final string urlstring = args;final string message = args;thread thread1 = new thread(){public void run(){try{url url = new url(urlstring);urlconnection connection =url.openconnection();inputstreamreader isr = newinputstreamreader(connection.getinputstream());bufferedreader reader =new bufferedreader(isr);int count = 0;while (reader.read() != -1){count++;}system.out.println("size is : "+ count);reader.close();} catch (malformedurlexception e){system.err.println("bad url: "+ urlstring);} catch (ioexception e){system.err.println("i/o problems");}}};thread1.start();runnable runnable = new runnable(){public void run(){while(true){system.out.println(message);try{thread.sleep(500);} catch (interruptedexception e){}}}};thread thread2 = new thread(runnable);thread2.start();try {system.out.println("press enter to stop");system.in.read(new byte);} catch (ioexception e){system.out.println("i/o problems");}system.exit(0);}}