《Thinking in java》阅读笔记(7)-并发

myhalfsea posted @ 2011年3月04日 03:08 in JAVA , 1745 阅读

线程是全新的,理解线程,对程序员的境界可谓是很大的一个飞跃。

我遇到了问题,先看一个正确的程序:
public class Fibonacci  implements Runnable{
    
    private int n;
    private long[] a = new long[100];
    Fibonacci(){}
    public Fibonacci( int n ){
        this.n = n;
        a[0] = 1;
        a[1] = 1;
        for( int i = 2; i < a.length; i++ )
            a[i] = a[i-1] + a[i-2];
    }
    @Override
    public void run() {
        for( int i = 0; i < n; i++ ) {
            System.out.println( n  + "列: "+ a[i]);
            Thread.yield();
        }
    }
}

public class MainThread {
    public static void main(String[] args) {
        for( int i = 1; i <= 3; i++ ){
            Thread d = new Thread( new Fibonacci(3*i));   // 1
            d.start();   // 2
        }
    }
}

输出为顺序混乱的结果,正确的结果。但是,若将1、2换成:Fibonacci f = new Fibonacci(3*i); f.run(); 则输出结果是顺序的;我知道是因为Thread.yield()的原因,但是,我应该怎么改才正确呢?

Executor:

java.util.concurrent 包中的执行器Executor 可以为你管理Thread 对象,从而简化并发编程。Executor在客户端和任务执行之间提供了间接层。与客户端直接执行代码不同,这个Executor将执行任务。Executor 允许你管理异步任务的执行,而无须显示的管理线程的生命周期。是Java Se5/6中启动任务的优选方法。

将main()改为:

        ExecutorService sec = Executors.newCachedThreadPool();
        for( int i = 1; i <= 3; i++ )
            sec.execute( new Fibonacci(i*3) );   
        sec.shutdown(); //执行完后,尽快退出,防止新的任务提交给这个executor。

 

可见,没有重复的创建Thread.

99-networks.com 说:
2023年4月16日 16:16

Find the relavant home / business based BSNL high speed broadband plans in UP East telecom delivering the best internet over copper / coaxial/ optical fiber network broadband services at lowest charges, Verify the low cost suitable unlimited. We 99-networks have a different Policy for its services and these are the important Policies concerns that are considered for using the website. Customers can anytime check this Privacy Policy listed on the website so 99-networks.com that they can be assured how their data is being used by the website. In the same manner.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta
Butterfly Theme | Design: HRS Hersteller of mobile Hundeschule.