加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Thread  三种创建方法

(2014-06-10 13:39:46)
标签:

java

thread

分类: android
方法一: 
建立Thread的子类,重构run方法。然后构建一个实例,调用start函数创建Thread。
class PrimeThread extends Thread {
     long minPrime;
     PrimeThread(long minPrime) {
                    this.minPrime = minPrime; }
     public void run() { // compute primes larger than minPrime  . }
}
PrimeThread p = new PrimeThread(143); p.start();
 
方法二:
创建接口Runnable的子类,重构方法run。建立一个实例,用Thread启动一个进程。
class PrimeRun implements Runnable {
      long minPrime;
      PrimeRun(long minPrime) {
               this.minPrime = minPrime;
}
      public void run() { // compute primes larger than minPrime  . }
}
PrimeRun p = new PrimeRun(143); new Thread(p).start();
或者 new Thread(new PrimeRun(143)).start;
 
方法二可以更简洁为:
new Thread(new Runnable(){public void run(){//// compute primes larger than minPrime }}).start();
方法三:

使用Timer和TimerTask组合
Timer类本身就是一个线程,不过这个线程用来实现调用其他线程的。TimerTask类一个抽象类,该类实现了Runnable接口。Timer通过schedule启动线程;线程的程序在重写的run方法中。
package test_java;
public class Thread2{
 public static void main(String[] args) {
  Timer tm = new Timer();
  MyTimerTask mtask = new MyTimerTask("thresd1:");
  tm.schedule(mtask, 0);
  //不定义对象,直接调用
  new Timer().schedule(new MyTimerTask("thread2:"), 500);
 }
}
//实现TimerTask
package test_java;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask{
 String s;
 public MyTimerTask(String s){
  this.s = s;
 }
 
 public void run(){
  try{
   for (int i=0; i<10; i++){
    Thread.sleep(200);
    System.out.println(s + i);
   }
  }catch(Exception ex){}
 }
}
 
一个Timer启动的多个TimerTask之间会存在影响,当上一个线程执行完成时,会阻塞后续线程的执行。要实现多个线程同时运行需要运行多个Timer。例如下面区别:
  //先执行thread1,然后执行thred2 
  Timer tm = new Timer();
  MyTimerTask mtask1 = new MyTimerTask("thresd1:");
  MyTimerTask mtask2 = new MyTimerTask("thresd2:");
  tm.schedule(mtask1, 500);
  tm.schedule(mtask2, 500);
                   区别:
  // thread1 thread2同时执行
  new Timer().schedule(new MyTimerTask("thread1:"), 500);
  new Timer().schedule(new MyTimerTask("thread2:"), 500);
 

0

阅读 收藏 喜欢 打印举报/Report
前一篇:java-synchronized
后一篇:Socket流程
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有