java Thread:利用Thread类实现多线程

 public class UsingThread {

 /**
  * @param args
  */
 
 //创建一个新进程类
 /*public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("main thread started");
  FactorialThread2 f=new FactorialThread2(10);
  f.start();
  System.out.println("main thread end");
 }
}//usingthread
    class FactorialThread2 extends Thread
    {
     private int num;
     public FactorialThread2(int num)
     {
      this.num=num;
     }
     
     public void run()
     {
      int i=num;
      int result=1;
      System.out.println("new thread started");
      while(i>0)
       {result*=i;
            i-=1;}
      System.out.println("The factorial of"+num+"is"+result);
      System.out.println("new thread ends");
     }
     */
 
 
 //创建3个新线程,每个线程睡眠一段时间(0~6秒),然后结束
 public static void main(String[] args)
 {
  System.out.println("Starting thread");
  TestTread t1=new TestTread("t1");
  TestTread t2=new TestTread("t2");
  TestTread t3=new TestTread("t3");
  t1.start();
  t2.start();
  t3.start();
  System.out.println("threads starts,main ends/n");
 }
}//usingTread
 class TestTread extends Thread
 {
  private int sleepTime;
  public TestTread(String name)
  {
   super(name);
   sleepTime=(int)(Math.random()*6000);
   
  }
  public void run(){
   try {
    System.out.println(this.getName()+" going to sleep for "+sleepTime);
    Thread.sleep(sleepTime);
   } catch (InterruptedException e) {}
    // TODO Auto-generated catch block
    System.out.println(getName()+" finished");
   
  }
 }
 /*心得:

1.从Thread类派生一个类,并创建这个类的对象,就可以产生一个新的线程

2.在派生类中需要重写run()方法,

3.调用sleep(long)可以令线程暂停long ms

4.继承Thread的派生类创建对象后,调用它的start()即可以运行一个新线程

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值