例1是通过继承thread类来实现的,定义一个线程类,该类继承thread类并重写其中的run()方法。
例2是通过实现接口Runnable
例1:
class subThread extends Thread
{
public subThread(String str)
{
super(str); //调用父类构造函数
}
public void run() //重写父类中的run()函数
{
System.out.println("线程:"+getName()+"开始运行";);
for(int i=1;i<=26;i++)
{
System.out.println(i);
try //捕获异常
{
sleep(100);//休息100毫秒-时间片
}
catch(InterruptedException e)//处理异常
{
System.out.println("线程"+getName()+"异常";);
}
}
}
}
class thread extends Thread
{
public thread(String str)//线程2的构造函数
{
super(str);
}
public void run()//run()方法
{
System.out.println("线程:"+getName()+"开始运行";);//疑惑:getName()是哪个类的方法啊?怎么就直接调用了啊?父类thread的?
for(char ch='A';ch<='Z';ch++)
{
System.out.println(ch);
try
{
sleep(100);
}
catch(InterruptedException e)
{
System.out.println("线程"+getName()+"异常";);
}
}
}
public static void main(String args[])
{
new subThread("1";).start();//初始化这个类的实例时,省略了其中的目标对象参数
new thread("2";).start();
}
}
此例是通过继承thread类来实现的,
定义一个线程类,该类继承thread类并重写其中的run()方法
例2:通过实现接口Runnable
class subThread implements Runnable
{
Thread thread1=new Thread(this,"1";);//初始化一个线程类的对象,this就是当前类的对象,作为目标对象
public void run() //重写父类中的run()函数
{
System.out.println("线程:"+thread1.getName()+"开始运行";);
for(int i=1;i<=26;i++)
{
System.out.println(i);
try //捕获异常
{
thread1.sleep(100);//休息100毫秒-时间片
}
catch(InterruptedException e)//处理异常
{
System.out.println("线程"+thread1.getName()+"异常";);
}
}
}
}
class threadtest implements Runnable
{
Thread thread2=new Thread(this,"2";);
public void run()//run()方法
{
System.out.println("线程:"+thread2.getName()+"开始运行";);
for(char ch='A';ch<='Z';ch++)
{
System.out.println(ch);
try
{
thread2.sleep(100);
}
catch(InterruptedException e)
{
System.out.println("线程"+thread2.getName()+"异常";);
}
}
}
public static void main(String args[])
{
Thread thread1=new Thread(new subThread());//用new subThread()生成一个subThread类的对象,此对象作为Thread类构造函数的目标对象参数,此参数是必须的
thread1.start();//启动线程
Thread thread2=new Thread(new threadtest());
thread2.start();
}
}