多线程中,锁设置为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);
}
}
}
}
}

解决方案 »

  1.   


    Mythread t1 = new Mythread("hello");

    Thread tt=new Thread(t1,"hello2");
    Thread t2=new Thread(t1,"world");
    类似这样才对
      

  2.   


    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);
    }
    }
    }
    }
    }
      

  3.   

    this代表当前对象,你new了两次就有两个对象,即两把锁,可以用static Object obj=new Object()的obj来代替
      

  4.   

    this是当前对象,你new两个就是不同的对象了