一个关于多线程的简单例子(两种实现方法)

例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();
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值