多线程中,锁设置为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);
}
}
}
}
}
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);
}
}
}
}
}
解决方案 »
- 问个弱弱的问题,Java中遍历数组的原理!
- 菜鸟求助io问题
- java对文件加密和解密的原理是什么?
- 单线程 多线程 同步 异步四个概念放在一起如何理解?
- 请问那里可以下载这些包org.mmocore.network???????
- 数据转换问题!
- 怎么将网上抓回的网页保存在本地
- <<thinking in Java>>第4章 210例程 Garbage.java 不理解!!!
- 如何搜索带"_"或"%"的字符串
- 我用applet读sql 2000数据库上的数据,在jb8测试上面好好的,为何在网页上面就不能正常?
- java学习中遇到一些题不会解,求大神教教
- 初步编写的Java坦克大战代码,未实现敌人坦克的发射和爆炸效果,求解答?
Mythread t1 = new Mythread("hello");
Thread tt=new Thread(t1,"hello2");
Thread t2=new Thread(t1,"world");
类似这样才对
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);
}
}
}
}
}