函数既然已经 声明为同步 那么函数体内是否不需要延迟操作呢 比如说 :
public void synchronized info()
{
Thread.sleep(100);
……
}
Thread.sleep(100)这句还有意义吗?
public void synchronized info()
{
Thread.sleep(100);
……
}
Thread.sleep(100)这句还有意义吗?
调试欢乐多
public static void main(String[] args) {
new ClockThread("rene").start();
new ClockThread("bobo").start();
}
}class ClockThread extends Thread {
private String name; public ClockThread(String name) {
this.name = name;
} public synchronized void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name + "---------------" + i);
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
}
}
}
}这里加锁,好像没什么用new ClockThread("rene").start();
new ClockThread("bobo").start();new了不同的线程对象,各自用各自的锁
输出为:
---------------------------------
rene---------------0
bobo---------------0
rene---------------1
bobo---------------1
bobo---------------2
rene---------------2
rene---------------3
bobo---------------3
rene---------------4
bobo---------------4
bobo---------------5
rene---------------5
bobo---------------6
rene---------------6
bobo---------------7
rene---------------7
bobo---------------8
rene---------------8
bobo---------------9
rene---------------9
public class test {
public static void main(String[] args) {
Object object = new Object();
new ClockThread("rene", object).start();
new ClockThread("bobo", object).start();
}
}class ClockThread extends Thread {
private String name;
private Object object = null; public ClockThread(String name, Object object) {
this.name = name;
this.object = object;
} public void run() {
synchronized (object) {
for (int i = 0; i < 10; i++) {
System.out.println(name + "---------------" + i);
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
}
}
}
}
}这里2个线程用的同步锁对象为同一个:
Object object = new Object();输出结果:
//-------------------------
rene---------------0
rene---------------1
rene---------------2
rene---------------3
rene---------------4
rene---------------5
rene---------------6
rene---------------7
rene---------------8
rene---------------9
bobo---------------0
bobo---------------1
bobo---------------2
bobo---------------3
bobo---------------4
bobo---------------5
bobo---------------6
bobo---------------7
bobo---------------8
bobo---------------9
在同步代码处
Thread.sleep();
当前线程转换睡眠状态
但占用的锁没有释放的
-----------
就看其他获得时间片的线程
要跑的代码
是否为同步的
是否跟被sleep()的线程使用相同的锁
另外:
如果其他获得时间片的线程
要跑的代码
是否为同步的
是否跟被sleep()的线程使用相同的锁 这个有什么关系吗