java 并发正题详解

java 并发主题详解

并发是计算机科学里的一个基本课题,本篇文章将针对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 线程间协作: