你的位置:首页 > Java教程

[Java教程]《多线程简单的应用》


  好,谈到线程的应用,我们需要先知道线程的创建。线程的创建用两种方式:一、继承Thread类  二、声明实现Runnable方法 

  方法一:

package thread;//继承Thread类public class PracticeThread extends Thread {  public int judge;  public PracticeThread(int judge) {    super();    this.judge = judge;  }  @Override  public void run() {    if (judge < 0) {      for (char ch = 'a'; ch < 'z'; ch++) {        System.out.print(" " + ch);      }    } else {      for (char ch = 'A'; ch < 'Z'; ch++) {        System.out.print(" " + ch);      }    }  }}

  方法二:

package thread;public class PracticeThreadt implements Runnable {  public int judge;  public PracticeThreadt(int judge) {    super();    this.judge = judge;  }  @Override  public void run() {    if (judge < 0) {      for (char ch = 'a'; ch < 'z'; ch++) {        System.out.print(" " + ch);      }    } else {      for (char ch = 'A'; ch < 'Z'; ch++) {        System.out.print(" " + ch);      }    }  }}

  而线程的启动也有两种方式:

package thread;public class Test {  /**   * @param args   */  public static void main(String[] args) {    // TODO Auto-generated method stub     PracticeThread pt = new PracticeThread(0) ;     PracticeThread pt2 = new PracticeThread(-1) ;    /* 线程实现方法一 */     pt.start() ;     pt2.start() ;    /* 线程实现方法二 */     new Thread(pt).start() ;     new Thread(pt2).start() ;    for (int i = 0; i < 5; i++) {      BanZhuan<Object> bz = new BanZhuan<Object>(5);      bz.start();    }  }}

  我们知道怎么创建与启动线程了,那么需要知道线程也是有优先级的。最低优先级是:MIN_PRIORITY(1)  默认优先级是:NORM_PRIOBITY(5)  最高优先级是:MAX_PRIOBITY(10)  线程名默认为:Thread-(0-max) ——如:Thread1、Thread2。。。。。