线程同步机制
2016-03-08 15:01
495 查看
一.当多个线程访问同一份相同的数据,会出现线程安全问题,也就是第一个线程还没有处理完成,另一个线种也执行这个方法。
synchronized关键字放在方法返回类型之前,或者在synchronized括号里面放同一个对象;通用的方法是放类的字节码。
以下举例说明
class Test{
public static void main(String[] args) {
new Test().init();
}
public void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("dingsi");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("huahua");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
class Outputer{
public void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
结果如下:
如果把上面打印的方法改为
public synchronized void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
或者
public void outPut(String name){
int length = name.length();
synchronized (Test.class) {
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
}
System.out.println();
}
synchronized关键字放在方法返回类型之前,或者在synchronized括号里面放同一个对象;通用的方法是放类的字节码。
以下举例说明
class Test{
public static void main(String[] args) {
new Test().init();
}
public void init() {
final Outputer outputer = new Outputer();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("dingsi");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
outputer.outPut("huahua");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
class Outputer{
public void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
结果如下:
如果把上面打印的方法改为
public synchronized void outPut(String name){
int length = name.length();
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
或者
public void outPut(String name){
int length = name.length();
synchronized (Test.class) {
for(int i = 0;i<length;i++){
System.out.print(name.charAt(i));
}
}
System.out.println();
}
相关文章推荐
- 我的fckeditor实践
- struts2 默认Action
- 读取assets文件
- MySQL 调编码
- Win7右键没有新建Word、excel、powerpoint
- 设备管理员功能介绍
- Android canvas.save()和canvas.restore()的理解
- CollectionFramework
- 20160308001 GridView的Sorting排序
- 监控工具TCPMon的使用方法
- 数据分析
- Android学习笔记之Fast Json的使用
- 产品经理最好用的工具都在这里了
- [转载]彻底弄清struct和typedef struct
- MySQL timestamp 的一个坑
- CPU和SoC的关系和区别
- PHP版本--HTTP session cookie原理及应用
- ORA-02266: unique/primary keys in table referenced by enabled foreign keys
- ubuntu 12.04下搭建web服务器(MySQL+PHP+Apache) 教程
- fckeditor使用(转)