您的位置:首页 > 编程语言 > Java开发

java 并发主题详解

2013-01-18 08:32 281 查看
并发是计算机科学里的一个基本课题,本篇文章将针对JAVA的并发分四个主题讨论一下多线程在JAVA里的写法和用处。四个课题分别是:线程的定义;共享受限资源;线程间协作;性能调优。

1 线程定义:

new Thread(new Runnable(){

            public void run() {

                /*

                 * 希望线程做什么事情,在这里写就好;对本写法进行拆分,可以有别的写法

                 */

            }          

}).start();

2 共享资源受限:

说白了就对共享的资源加锁,让同时只有一个线程可以访问该资源,锁从类型上分为三种:对象锁、类锁、代码块锁。

2.1 对象锁

public class Counter {

    private Long id = 0L;

    public synchronized void increase(){

        id++;

    }

    public synchronized void printCounter(){

        System.out.println(this.id);

    }

}

类Counter中有两个同步方法:increase()、printCounter()。在同一个对象上,两个方法不能同时执行,互相排斥。不同对象上当然可以。

2.2 类锁

public class Generator {

    private static Long id = 0L;

    

    public synchronized static void next(){

        id++;

    }

    

    public synchronized static void print(){

        System.out.println(Thread.currentThread().getName());

        System.out.println(id);

    }

    

}

类Generator中有两个同步方法:next()、print()。在同一个对象上,两个方法不能同时执行,互相排斥。不同对象上也不能同时执行,互相排斥。

2.3 代码块锁

public class CatalogContentSyn extends HttpServlet {

    protected void service(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

        synchronized ("lockcata") {

            /*

             * 这里有一个读写数据库的操作,所有访问到这个地方的时候,

             * 前一个访问必须先执行完,后到的访问才能执行。如果前一个访问没有完成本块代码,

             * 后到访问阻塞。

             */

        }

    }

}

前一个访问必须先执行完,后到的访问才能执行。如果前一个访问没有完成本块代码, 后到访问阻塞。

3 线程间协作:

public class ListStack {

    private  ArrayList<Integer>

        list = new ArrayList<Integer>(100);

    private Boolean hasWait = false;

    /*

     * 压栈方法,如果栈中有数据,并且有线程在等待,唤醒其它线程

     */

    public synchronized  void push(){

        Random rand = new Random();

        list.add(rand.nextInt(10000));

        if(list.size() > 0 && hasWait){

            this.notifyAll();

            hasWait = false;

        }

    }

    /*

     * 出栈方法:从栈里那第一条数据,如果发现没有数据,线程等待    

     */

    public synchronized  Integer pop(){

        Integer firstElement = null;

        if(null != list && list.size() > 0){

            firstElement = list.get(0);

            list.remove(0);

        }else{

            try {

                hasWait = true;

                this.wait();

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

        return firstElement;

    }

}

简单的来说线程间协作就是某种情况下线程1发生等待,某些条件下,等待线程又被别的线程唤醒。

性能调优,请参看:

多线程同步与性能一

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息