synchronized关键字小结(一)
2016-06-09 16:34
330 查看
1. synchronized同步方法
1) synchronized修饰方法,表示方法是同步的,当某线程进入并拿到当前整个对象的锁时
a. 其他synchronized方法排队等锁
b. 非synchronized方法可异步执行
示例代码(折叠)
View Code
运行结果:
1) synchronized修饰方法,表示方法是同步的,当某线程进入并拿到当前整个对象的锁时
a. 其他synchronized方法排队等锁
b. 非synchronized方法可异步执行
示例代码(折叠)
package com.khlin.thread; public class SynchronizedStatic { public static void main(String[] args) { ThreadAAA threadAAA = new ThreadAAA(); threadAAA.setName("ThreadAAA"); threadAAA.start(); try { Thread.sleep(500L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ThreadBBB threadBBB = new ThreadBBB(); threadBBB.setName("ThreadBBB"); threadBBB.start(); } } class StaticService { public synchronized static void methodA() { String threadname = Thread.currentThread().getName(); System.out.println("invoking methodA. " + threadname); try { Thread.sleep(1000L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("finish methodA. " + threadname); } public synchronized static void methodB() { String threadname = Thread.currentThread().getName(); System.out.println("invoking methodB. " + threadname); System.out.println("finish methodB. " + threadname); } } class ThreadAAA extends Thread { public void run() { StaticService.methodA(); } } class ThreadBBB extends Thread { public void run() { StaticService.methodB(); } }
View Code
运行结果:
相关文章推荐
- bootstrap学习总结-js组件(四)
- SQLAlchemy使用说明之ORM
- Java并发编程之——CyclicBarrier的使用
- win10 uefi Ubuntu14.04双系统
- matlab练习程序(粒子群优化PSO)
- 77.PS接收来自PL的按键中断
- ORA-01034: ORACLE not available
- 关于c的printf和scanf的知识点----菜鸟笔记(1)
- mysql5.7,utf-8字符编码问题
- 04_登陆注册
- 如何使用hugo搭建个人博客(三):添加follow与修改share的方式
- 边框
- MyBatis常用的jdbcType类型
- ros_arduino_bridge功能包集的使用错误及解决方法总结
- URAL 1099 一般图带花树匹配
- AVLTree
- Sizeof与Strlen的区别与联系
- ubuntu16.04+opencv3.1配置
- 复制文件时,文件夹中有同名的文件时,自动给文件重命名
- 03_模拟DVD