java多线程之synchronized(线程同步)

一、线程同步,主要应用synchronized关键字:

public class TraditionalThreadSynchorinzed {
    public static void main(String[] args) {
        new TraditionalThreadSynchorinzed().init();
    }
    
    private void init(){
        final Outputer outputer = new Outputer();
        new Thread(new Runnable(){
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output("zhangxiaoxiang");
                }
                
            }
        }).start();
        
        new Thread(new Runnable(){
            @SuppressWarnings("static-access")
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output3("lihuoming");
                }
                
            }
        }).start();    
    }
    /**
     *    synchronized 关键字可以使线程同步。如果它包含一个代码块,那么跟在括号后面的参数必须
     * 保证唯一,不能使可变得。如果它作用在方法上,那么默认它的锁对象是this关键字。如果它作用在静态
     * 方法上,它的锁对象是当前类字节码。
     */
    static class Outputer{
        /**
         * output和output3同步,如果将output括号里面的字节码改成this关键字,那么output
         * 和output2同步。
         * 
         */
        public void output(String name){
            int len = name.length();
            synchronized (Outputer.class) 
            {
                for(int i=0;i<len;i++){
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
        }
        
        public synchronized void output2(String name){
            int len = name.length();
            for(int i=0;i<len;i++){
                    System.out.print(name.charAt(i));
            }
            System.out.println();
        }
        
        public static synchronized void output3(String name){
                int len = name.length();
                for(int i=0;i<len;i++){
                        System.out.print(name.charAt(i));
                }
                System.out.println();
        }    
    }
}
View Code

二、生产者与消费者问题,采用了synchronized、wait和notify:

public class CreateAndCoustomer {

    /**
     * @param args
     */
    public static void main(String[] args) {
        final ProduceCollection pc = new ProduceCollection();
         for(int i = 0;i<2;i++){
             new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        while(true){
                            pc.create();
                        }

                    }
                }).start();
         }
         for(int i = 0;i<2;i++){
             new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while(true){
                            pc.delete();
                        }
                    }
                }).start();
         }        
    }
}

class ProduceCollection {
    List<String> coll = new ArrayList<String>();
    int count = 10;

    public synchronized void create() {
        while(this.coll.size()>9){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        coll.add("zhangsan");
        System.out.println(Thread.currentThread().getName()
                + "向池子添加一个产品,当前产品的个数" + coll.size());
        this.notify();
    }

    public synchronized void delete() {
        while(this.coll.size()<1){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        coll.remove(0);
        System.out.println(Thread.currentThread().getName() + "消费了一个产品,当前产品的个数"
                + coll.size());
        this.notify();
    }
}
View Code
原文地址:https://www.cnblogs.com/lbangel/p/3186419.html