Java 线程 synchronized 学习
来源:互联网 发布:数据港 编辑:程序博客网 时间:2024/06/04 21:16
**synchronized** 关键字:当一个方法被synchronized关键字修饰的时候,该方法叫同步方法 Java中的每个对象都有一个锁(lock)或者叫监视器(monitor),当访问某个线程的访问synchronized 方法时,表示给该对象上锁,此时其他任何线程都无法访问该synchronized 方法,直到之前的那个线程执行完方法或者抛出异常,那个该对象的锁被释放掉,其他线程才可以访问该synchronized 方法public class ThreadTest { public static void main(String[] args) { Example example = new Example(); TheThread t1 = new TheThread(example); TheThread2 t2 = new TheThread2(example); t1.start(); t2.start(); }}class Example { public synchronized void execute() { for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello: " + i + " "); } } public synchronized void execute2() { for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("word: " + i + " "); } }}class TheThread extends Thread { private Example example; public TheThread(Example example) { this.example = example; } @Override public void run() { super.run(); example.execute(); }}class TheThread2 extends Thread { private Example example; public TheThread2(Example example) { this.example = example; } @Override public void run() { super.run(); example.execute2(); }}打印的顺序是hello: 0 hello: 1 hello: 2 hello: 3 hello: 4 hello: 5 hello: 6 hello: 7 hello: 8 hello: 9 word: 0 word: 1 word: 2 word: 3 word: 4 word: 5 word: 6 word: 7 word: 8 word: 9 从结果上看是有序的,也就是说如果一个对象有多个synchronized方法,某一个时刻某个线程已经进入某个synchronized 方法,那么该方法没有执行完之前,其他线程无法访问该对象的任何synchronized 方法,当然非synchronized 还是可以访问的。 将execute2方法改成static的 public synchronized static void execute2() 打印的结果如下: word: 0 hello: 0 hello: 1 word: 1 word: 2 hello: 2 word: 3 hello: 3 hello: 4 word: 4 hello: 5 word: 5 hello: 6 word: 6 原因分析:static修饰的方法或者变量不属于任何对象,属于类的,当synchronized 修饰一 个static方法时,锁的不是当前对象,而是当前对象所对应的class对象,而一个类不管有多少对象,其所对应的class对象只有一个。这个时候把execute方法也改成static,打印结果如下: hello: 0 hello: 1 hello: 2 hello: 3 hello: 4 hello: 5 hello: 6 hello: 7 hello: 8 hello: 9 word: 0 word: 1 word: 2 word: 3 word: 4 word: 5 word: 6 word: 7 word: 8 word: 9 再次验证,如果某个synchronized 方法是static的,当线程访问该方法时,它锁的并不是synchronized 方法所处在的对象,而是这个类的Class对象,而Java一个类的对象无论有多少个,Class对象始终只有一个,因此当多个线程访问同一个类多个对象的不同synchronized static方法时,执行的结果也是按照顺序的,也就是一个线程执行完毕后另外一个线程才能执行。
0 0
- Java 线程 synchronized 学习
- Java学习之线程锁--synchronized
- java线程:synchronized
- java 线程同步 synchronized
- java 线程同步 synchronized
- java synchronized 线程同步
- Java 线程同步 synchronized
- Java线程同步synchronized
- java---------线程-----synchronized
- java线程锁 synchronized
- JAVA -- 线程synchronized关键字
- java线程同步-synchronized
- java线程同步:synchronized
- java synchronized线程同步
- Java线程:Synchronized
- 【Java】 线程安全 synchronized
- JAVA 线程同步 synchronized
- java 线程 synchronized详解
- 树形结构的数据库表Schema设计
- 解决maven项目自动修改jdk版本问题
- 图像识别常用的数据库
- 只在某页面屏幕旋转,其他竖屏
- 文章标题
- Java 线程 synchronized 学习
- AES 代码实现
- UE4 三维点击事件
- 程序员提升效率的工具
- Swift 数值运算符
- VS2015使用小技巧 同时调试两个控制台程序
- cm12 for 三星n7100编译
- HTML表格导出到EXCEL
- SpringMVC入门第一个程序