我是线程的初学者.我不确切地知道线程对象调用sleep方法的三种不同类型的方式有什么区别.还可以请说明在哪种类型的情况下使用睡眠方法的方式存在限制
代码如下
// implementing thread by extending THREAD class//
class Logic1 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
Thread s = Thread.currentThread();
System.out.println("Child :"+i);
try{
s.sleep(1000); // these are the three types of way i called sleep method
Thread.sleep(1000); //
this.sleep(1000); //
} catch(Exception e){
}
}
}
}
class ThreadDemo1
{
public static void main(String[] args)
{
Logic1 l1=new Logic1();
l1.start();
}
}
Run Code Online (Sandbox Code Playgroud) 我试图创建一个五个线程,因此如果一个线程在一个对象上调用synchronized方法(在这种情况下是objsyn),那么所有其他线程应该等到线程完成对象.因此输出应该按顺序从线程1到线程5.但输出结果不合时宜.
class synctest extends Thread
{
public synchronized void display()
{
try{Thread.sleep(5000*((long)(Math.random())));}
catch(Exception e){}
System.out.println("From synchornized thread "+ Thread.currentThread().getName());
}
public synchronized void run()
{
synctest objsyn = new synctest();
objsyn.display();
}
public static void main(String args[])
{
synctest objsy = new synctest();
Thread t1 = new Thread(objsy,"Thread 1");
Thread t2 = new Thread(objsy,"Thread 2");
Thread t3 = new Thread(objsy,"Thread 3");
Thread t4 = new Thread(objsy,"Thread 4");
Thread t5 = new Thread(objsy,"Thread 5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Run Code Online (Sandbox Code Playgroud)