synchronized(this)的疑问。帮忙解释下吧,谢谢

chaoliu1024 2011-02-11 10:33:58
public void run(){
try{
for(int i = 15;i > 0;i--){
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this){ // 这里的synchronized(this)是指对象调用run()方法,还是wait()方法?
while(suspendFlag){
wait();
}
}
}
}


public void run()
{
synchronized(target){
target.call(msg); // 这里的synchronized(target)
// 是target对象调用call()方法,对吧
}
}


public class Thread1 implements Runnable {

public void run() {
synchronized (this) { // 这里的synchronized (this)是ta、tb分别调用run()方法?
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
}
}

public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread ta = new Thread(t1, "A");
Thread tb = new Thread(t1, "B");
ta.start();
tb.start();
}
}
...全文
79 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
huyong479072052 2011-02-12
  • 打赏
  • 举报
回复
synchronized(this){ // 这里的synchronized(this)是指对象调用run()方法,还是wait()方法?
while(suspendFlag){
wait();
}
这里重写了synchronized方法,你下面写的wait();
当然是调用wait();方法了,不过要当前对象拿到钥匙。
public void run()
{
synchronized(target){
target.call(msg); // 这里的synchronized(target)
// 是target对象调用call()方法,对吧
}
}
这个是对的
public void run() {
synchronized (this) { // 这里的synchronized (this)是ta、tb分别调用run()方法?
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
}
}

ta.start();
tb.start();
这里不一定是谁调用run方法,在本类中new的线程,你调用其start方法,他都会调用run方法
然后执行这个
synchronized (this) { // 这里的synchronized (this)是ta、tb分别调用run()方法?
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
SuperCodingMan 2011-02-11
  • 打赏
  • 举报
回复
this是指当前对象
class Apple{
private int a;
public Apple(int num){
this.a = num;//this 是指当前对象,即使多线程也是一样道理的
}
}
chaoliu1024 2011-02-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 supercodingman 的回复:]
synchronized 指的是在同一时刻,只有拿到“钥匙”的那个人才能操作被同步的对象,否则就排队等。
[/Quote]我知道这个道理,我想问的是this指的是哪个人?不要回答是本人。。本人是哪个人?
SuperCodingMan 2011-02-11
  • 打赏
  • 举报
回复
synchronized 指的是在同一时刻,只有拿到“钥匙”的那个人才能操作被同步的对象,否则就排队等。

62,615

社区成员

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

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