java 同步锁无效的解决办法

qq_39459185 2017-08-05 06:05:46
多线程中,锁设置为this,却没起到锁的作用,输出结果依然是不同步的,为什么呢?



package lianxi1_duoxiancheng_2;

public class CeShi {
public static void main(String[] args) {
Mythread t1 = new Mythread("hello");
Mythread t2 = new Mythread("world");
t1.start();
t2.start();
}

static class Mythread extends Thread {
private String data;

public Mythread(String data) {
this.data = data;
}

public void run() {
synchronized (this) {//此处的this没起到锁的作用
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((int) (Math.random() * 100));
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(data);
}
}
}
}
}
...全文
356 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
bcvb 2017-08-07
  • 打赏
  • 举报
回复
this是当前对象,你new两个就是不同的对象了
M义薄云天 2017-08-06
  • 打赏
  • 举报
回复
this代表当前对象,你new了两次就有两个对象,即两把锁,可以用static Object obj=new Object()的obj来代替
李德胜1995 2017-08-05
  • 打赏
  • 举报
回复

public class DD {
	private static final DD dd=new DD();
public static void main(String[] args) {
Mythread t1 = new Mythread("hello");
Mythread t2 = new Mythread("world");
t1.start();
t2.start();
}

static class Mythread extends Thread {
private String data;

public Mythread(String data) {
this.data = data;
}

public void run() {
synchronized (dd) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((int) (Math.random() * 100));
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(data);
}
}
}
}
}
xiaovhao 2017-08-05
  • 打赏
  • 举报
回复

Mythread t1 = new Mythread("hello");
	
	Thread tt=new Thread(t1,"hello2");
	Thread t2=new Thread(t1,"world");
类似这样才对
wautsns 2017-08-05
  • 打赏
  • 举报
回复
锁对象是两个不同的对象,有效就有鬼了,,,

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧