java中synchronized修饰的方法和代码块

来源:互联网 发布:圆方家居设计软件破解 编辑:程序博客网 时间:2024/06/05 02:51

Java中synchronized修饰的方法和代码块

    public class Test {        public static void main(String[] args) {            // 测试synchronized修饰的方法            new Thread(new Runnable() {                @Override                public void run() {                    Test.testsyncmethod();                }            }, "t1").start();            new Thread(new Runnable() {                @Override                public void run() {                    Test.testsyncmethod();                }            }, "t2").start();            // 测试synchronized修饰的代码块            final Test test = new Test();            new Thread(new Runnable() {                @Override                public void run() {                    test.testsyncCode();                }            }, "t1").start();            new Thread(new Runnable() {                @Override                public void run() {                    test.testsyncCode();                }            }, "t2").start();            // 测试synchronized(this)同步代码块            ThreadTest tt = new ThreadTest();            Thread t1 = new Thread(tt, "t1");            Thread t2 = new Thread(tt, "t2");            t1.start();            t2.start();        }        /***         * synchronized修饰的方法,并发线程同事调用时,一个时间内只有一个线程得到执行。其他线程必须等待当前线程执行完这个方法后才能执行         */        public static synchronized void testsyncmethod() {            for (int i = 0; i < 10; i++) {                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println(Thread.currentThread().getName() + " " + i);            }        }        /***         * synchronized修饰的方法,并发线程同事调用时,一个时间内只有一个线程得到执行。其他线程必须等待当前线程执行完这个方法后才能执行         */        public void testsyncCode() {            synchronized (this) {                for (int i = 0; i < 10; i++) {                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        }}class ThreadTest implements Runnable {    @Override    public void run() {        // synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块        synchronized (this) {            for (int i = 0; i < 5; i++) {                System.out.println(Thread.currentThread().getName() + " " + i);            }        }        System.out.println(Thread.currentThread().getName() + "--");    }}
1 0
原创粉丝点击