Chinaunix首页 | 论坛 | 博客
  • 博客访问: 600142
  • 博文数量: 96
  • 博客积分: 1464
  • 博客等级: 上尉
  • 技术积分: 1539
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-12 23:24
文章分类

全部博文(96)

文章存档

2013年(29)

2012年(53)

2011年(14)

分类: Java

2013-01-08 14:35:45

1.多线程的概念
2.java多线程的实现
3.线程生命周期
4.线程优先级
5.阻止线程运行
6.多线程的返回值

1.多线程的概念:
    多线程在较低层次上扩展了多任务的概念:一个程序同时执行多个任务。一个任务就是一个线程(thread)。可以同时运行一个以上线程的程序称为多线程程序(multithread)。

2.java多线程实现:
    java程序非常容易定义并同时执行多个线程。java.lang.Thread是java API的基本线程类。
    下面是两种方法定义线程,返回的都是一个Thread对象,run()方法是这个线程的主体部分:
        1.生成Thread类的子类,覆盖其中的run()方法,在实例化Thread子类。
        2.定义一个实现Runnable方法(比如定义一个run()方法)的类,再把这个Runnable对象的实例作为参数传给Thread()的构造函数。

点击(此处)折叠或打开

  1. final List list; // Some long unsorted list of objects; initialized elsewhere
  2. /** A Thread class for sorting a List in the background */
  3. class BackgroundSorter extends Thread {
  4.   List l;
  5.   public BackgroundSorter(List l) { this.l = l; } // Constructor
  6.   public void run() { Collections.sort(l); } // Thread body
  7. }

  8. // Create a BackgroundSorter thread
  9. Thread sorter = new BackgroundSorter(list);
  10. // Start it running; the new thread runs the run() method above while
  11. // the original thread continues with whatever statement comes next.
  12. sorter.start();

  13. // Here's another way to define a similar thread
  14. Thread t = new Thread(new Runnable() { // Create a new thread
  15.   public void run() { Collections.sort(list); } // to sort the list of objects.
  16. });
  17. t.start();
3.线程的生命周期:
    新生:new:线程对象已经创建,但还没有调用start()方法。
    可运行:runnable:线程有资格运行,但调度程序还没有把他选定为运行线程时所处的状态。当start()方法调用时,线程首先进入可运行状态。在线程运行之后或从阻塞、等待、睡眠状态回来后,也返回到可运行状态。
    运行:线程调度程序从可运行线程池中选择一个线程作为当前线程时线程所处的状态。这也是线程进入运行状态的唯一一种方式。
    阻塞:blocked:
    等待:waiting:
    计时等待:timed_waiting
    死亡:terminated:当线程的run()方法完成时就认为他死去了。线程一旦死亡就不能复生。


4.线程的优先级:
    线程存在优先级,范围在1-10间,默认是5,jvm线程调度程序是基于优先级的抢先调度机制。
    注意:当设计多线程应用程序时,一定不要依赖于线程的优先级。因为线性的调用优先级是没有保障的,
    Thread类中有三个常量,定义线程优先级范围
        static int MAX_PRIORITY:线程可以具有最高优先级
        static int MIN_PRIORITY:线程可以具有最低优先级
        static int NORM_PRIORITY:分配给线程的默认优先级
    设置线程优先级:
        Thread t = new MyThread();
        t.setPriority(7);
        t.start();


5.阻止线程运行:
    Thread.sleep(long  millis)  或 Thread.sleep(long millis, int nanos):线程睡眠时间
    Thread.yield():暂停当前线程,从新从可运行线程中选择线程执行。有可能原先的线程被选中继续执行。
    join(long millis) 或 join(long millis, int nanos):当前线程强行抢占资源最长可能的时间,

    Thread.sleep(long millis):强制睡眠多长时间,时间到后进入可运行状态,等待运行。
        使用该方法的目的:防止应为当前线程太耗时而阻碍其他线程的执行。使其他线程有机会执行。调用方法:
         /** 
* 一个计数器,计数到100,在每个数字之间暂停1秒,每隔10个数字输出一个字符串 

* @author leizhimin 2008-9-14 9:53:49 
*/
 
public class MyThread extends Thread { 

    public void run() { 
        for (int i = 0; i < 100; i++) { 
            if ((i) % 10 == 0) { 
                System.out.println("-------" + i); 
            } 
            System.out.print(i); 
            try { 
                Thread.sleep(1); 
                System.out.print("    线程睡眠1毫秒!\n"); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 

    public static void main(String[] args) { 
        new MyThread().start();    //注意这里的调用
    } 

   Thread.yield():暂停当前线程,当前线程进入可运行状态,从新从可运行线程中选择线程执行。有可能原先的线程被选中继续执行。

    join()方法:无参的join()方法表示知道该线程运行完,才执行其他线程,有参数则表示该线程最长执行多长时间,然后又从新选择线程执行。

6.多线程的返回值
    Runnable是执行工作的独立任务,但它不返回任何值
    如果希望任务完成后能返回一个值,在java se5中可使Callable接口,而不是Runnable接口。
    Callable是一种具有类型参数的泛型,它的类型参数表示的是从方法call()(而不是run())中返回的值。且必须使用ExecutorService.submit()方法调用它。submit()方法会产生Future对象,可以调用get()方法来获取该结果。
public class ReturnResult implements Callable{
private int id;
public ReturnResult(int id){
this.id = id;
}
public String call(){
return "result of ReturnResult "+id;
}
}

//有返回值的调用
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList> results = 
new ArrayList>();
for(int i=0;i<10;i++){
results.add(exec.submit(new ReturnResult(i)));
}
for(Future fs:results){
try{
System.out.println(fs.get());
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}finally{
exec.shutdown();
}
}



参考文献:多线程总结http://lavasoft.blog.51cto.com/62575/27069
                java编程思想
阅读(625) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~