当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机二级Java线程例子学习教程
发布时间:2011/12/28 9:48:31 来源:城市学习网 编辑:ziteng

7.2 Java线程例子

  7.2.1 显式定义线程

  在我们的单线程应用程序里,我们并没有看见线程,因为Java能自动创建和控制你的线程。如果你使用了理解Java语言的浏览器,你就已经看到使用多线程的Java程序了。你也许注意到两个小程序可以同时运行,或在你移动滚动条时小程序继续执行。这并不是表明小程序是多线程的,但说明这个浏览器是多线程的。多线程应用程序(或applet)可以 使 用 好几个执行上下文来完成它们的工作。多线程利用了很多任务包含单独的可分离的子任务 的特点。每一个线程完成一个子任务。

  但是,每一个线程完成子任务时还是顺序执行的。一个多线程程序允许各个线程尽快执行完它们。这种特点会有更好的实时输入反应。

  7.2.2 多线程例子

  下面这个例子创建了三个单独的线程,它们分别打印自己的“Hello World":

  //Define our simple threads.They will pause for a short time

  //and then print out their names and delay times

  public class TestThread extends Thread {

  private String whoami; //定义其属性

  private int delay;

  //Our constructor to store the name (whoami)

  //and time to sleep (delay)

  public TestThread(String s, int d) { //定义了一个线程的构造函数

  whoami = s;

  delay = d;

  }

  //Run - the thread method similar to main()

  //When run is finished, the thread dies.

  //Run is called from the start() method of Thread

  public void run() { //运行线程

  //Try to sleep for the specified time

  try {

  sleep(delay); //让线程进行睡眠

  }

  catch(InterruptedException e) {

  }

  //Now print out our name

  System.out.println("Hello World!"+whoami+""+delay);

  }

  }

  /** * Multimtest. A simple multithread thest program */

  public static void main(String[] args) {

  TestThread t1,t2,t3;

  //Create our test threads

  t1 = new TestThread("Thread1",(int)(Math.readom()*2000)); //实例化线程

  t2 = new TestThread("Thread2",(int)(Math.readom()*2000));

  t3 = new TestThread("Thread3",(int)(Math.readom()*2000));

  //Start each of the threads

  t1.start(); //启动线程

  t2.start();

  t3.start();

  }

  }

  7.2.3 启动一个线程

  程序启动时总是调用main()函数,因此main()是我们创建和启动线程的地方:

  t1 = new TestThread("Thread1", (int)(Math.readom()*2000));

  这一行创建了一个新的线程。后面的两个参数传递了线程的名称和线程在打印信息前的延 时时间。因为我们直接控制线程,我们必须直接启动它:

  t1.start();

  7.2.4 操作线程

  如果创建线程正常,t1应包含一个有效的执行线程。我们在线程的run()函数里控制线程。 当进 入run()函数,我们便可执行里面的任何程序。run()好象main()一样。 当执行完,这个线程也就结束了。在这个例子里,我们试着延迟一个随机的时间(通过参数传递);

  sleep(delay);

  sleep()函数只是简单地告诉线程休息多少个毫秒时间。如果你想推迟一个线程的执行, 应使用sleep()函数。 当线程睡眠是sleep()并不占用系统资源。其它线程可继续工作。当延迟时间完毕,它将打印"Hello World"和线程名称及延迟时间。

  7.2.5 暂停一个线程

  我们经常需要挂起一个线程而不指定多少时间。例如,如果你创建了一个含有动画线程的小程序。也许你让用户暂停动画至到他们想恢复为止。你并不想将动画线程仍调,但想让它停止。象这种类似的线程你可用suspend()函数来控制:

  t1.suspend();

  这个函数并不永久地停止了线程,你还可用resume()函数重新激活线程:

  t1.resume();

  7.2.6 停止一个线程

  线程的最后一个控制是停止函数stop()。 我们用它来停止线程的执行:

  t1.stop();

  注意:这并没有消灭这个线程,但它停止了线程的执行。并且这个线程不能用t1.start()重新启动。在我们的例子里,我们从来不用显式地停止一个线程。我们只简单地让它执行完而已。很多复杂的线程例子将需要我们控制每一个线程。在这种情况下会使用到stop()函数。如果需要,你可以测试你的线程是否被激活。一个线程已经启动而且没有停止被认为是激活的。t1.isAlive() 如果t1是激活的,这个函数将返回true. [NextPage]

  7.2.7 动画例子

  下面是一个包含动画线程的applet例子:

  import java.awt.*;

  import java.awt.image.ImageProducer; //抽象类Image是表示图形图像的所有类的超类。ImageProducer可为Image生成图像数据的对象的接口。每幅图像都包含一个用于在需要时重构图像的 ImageProducer(例如在缩放 Image 的新大小时,或者在请求 Image 的宽度或高度时)。

  import java.applet.Applet;

  public class atest3 extends Applet implements Runnable {

  Image images[];

  MediaTracker tracker;

  int index = 0;

  Thread animator;

  int maxWidth,maxHeight;

  //Our off-screen components for double buffering.

  Image offScrImage;

  Graphics offScrGC;

  //Can we paint yes?

  boolean loaded = false;

  //Initialize the applet. Set our size and load the images

  public void init() {

  //Set up our image monitor

  tracker = new MediaTracker(this);

  //Set the size and width of our applet

  maxWidth = 100;

  maxHeight =100;

  images = new Image[10];

  //Set up the double-buffer and resize our applet

  try {

  offScrImage = createImage(maxWidth,maxHeight);

  offScrGC = offScrImage.getGraphics();

  offScrGC.setColor(Color.lightGray);

  offScrGC.fillRect(0,0,maxWidth,maxHeight);

  resize(maxWidth,maxHeight);

  }

  catch (Exception e) {

  e.printStackTrace();

  }

  //load the animation images into an array

  for (int i=0;i<10;i++) {

  String imageFile = new String ("images/Duke/T" +String.valueOf(i+1) +".gif");

  images[i] = getImage(getDocumentBase(),imageFile):

  //Register this image with the tracker tracker.addImage(images[i],i);

  }

  try {

  //Use tracker to make sure all the images are loaded

  tracker.waitForAll();

  }

  catch (InterruptedException e) {

  }

  loaded = true;

  }

  //Paint the current frame.

  public void paint (Graphics g) {

  if (loaded) {

  g.drawImage(offScrImage,0,0,this);

  }

  }

  //Start ,setup our first image

  public void start() {

  if (tracker.checkID (index)) {

  offScrGC.drawImage (images[index],0,0,this);

  }

  animator = new Thread(this);

  animator.start();

  }

  //Run,do the animation work here.

  //Grab an image, pause ,grab the next...

  public void run() {

  //Get the id of the current thread

  Thread me = Thread.currentThread();

  //If our animator thread exist,and is the current thread...

  while ((animatr!= null) && (animator==me)) {

  if ( tracker.checkID (index)) {

  //Clear the background and get the next image

  offScrGC.fillRect(0,0,100,100);

  offScrGCdrawImage(images[index],0,0,this);

  index++;

  //Loop back to the beginning and keep going

  if (index>= images.length) {

  index = 0;

  }

  }

  //Delay here so animation looks normal

  try {

  animator.sleep(200);

  }

  catch (InterruptedException e) {

   //

  }

  //Draw the next frame

  repaint();

  }

  }

  }

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved