Jav*_*ast 1 java multithreading thread-sleep
我工作的主题,当一个问题击中我的mind..If我们可以直接调用run()方法与类的像那么任何普通方法的对象为什么我们需要调用Thread.start()调用的run()方法..我尝试了两种方法,并且两者都得到了相同的结果
首先直接调用run()方法
class Abc extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Abc");
}
try
{
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Error : "+ e);
}
}
}
class Xyz extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println("Xyz");
}
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Error : "+ e);
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
Abc ob=new Abc();
Xyz oc=new Xyz();
ob.run();
oc.run();
}
}
Run Code Online (Sandbox Code Playgroud)
通过调用Thread.start()进行第二次尝试
public class ThreadDemo
{
public static void main(String[] args)
{
Abc ob=new Abc();
Xyz oc=new Xyz();
Thread t1,t2;
t1=new Thread(ob);
t2=new Thread(oc);
t1.start();
t2.start();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
241 次 |
| 最近记录: |