package Test;public class TestThreadSync implements Runnable{ public TestThreadSync(){
}
Sync sync = new Sync();
@Override
public void run() {
synchronized (sync){
sync.function();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String args[]){
Thread t1 = new Thread(new TestThreadSync());
Thread t2 = new Thread(new TestThreadSync());
t1.start();
t2.start();
}
}class Sync{
public Sync(){
}
public void function(){
System.out.println(Thread.currentThread().getName()+"正在运行");
}
}
我的想法是t1,t2启动,打印“Thread-0正在运行”5秒钟后再打印“Thread-1在运行”为什么他们同时打印出来呢 synchronized不是把对象锁定了吗5秒后才释放的?请各位指点下
}
Sync sync = new Sync();
@Override
public void run() {
synchronized (sync){
sync.function();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String args[]){
Thread t1 = new Thread(new TestThreadSync());
Thread t2 = new Thread(new TestThreadSync());
t1.start();
t2.start();
}
}class Sync{
public Sync(){
}
public void function(){
System.out.println(Thread.currentThread().getName()+"正在运行");
}
}
我的想法是t1,t2启动,打印“Thread-0正在运行”5秒钟后再打印“Thread-1在运行”为什么他们同时打印出来呢 synchronized不是把对象锁定了吗5秒后才释放的?请各位指点下
public static void main(String args[])
{
TestThreadSync tts= new TestThreadSync();//只创建一个TestThreadSync对象,
Thread t1 = new Thread(tts); //里面的sync是一个。才能起到同步的作用。
Thread t2 = new Thread(tts);
t1.start();
t2.start();
}
应该是在run方法外的方法里面加上synchronized,这时候两个线程就不能同时访问该方法了。
改为static即可
2、Thread.sleep(5000);每个线程都等了5秒,不是只有Thread-1等5秒
3、要想实现你要的效果,要用wait,notify组合