JAVA中建立多线程的典型例子

来源:互联网 发布:中华抢红包软件好用吗 编辑:程序博客网 时间:2024/04/28 23:41

JAVA中建立多线程,无非两种方式,一是继承自thread类,另一种是实现runnable接口,下面两个例子很典型,可以复习下
1、继承自thread类
  

public class j02140301 extends Thread  // 步骤 1
{
  public void run()   // 步骤 2 ,覆盖继承自 Thread 的 run()
  {
    while(true)
    { 
      System.out.print("X ");
      //....
      try
      {
        Thread.sleep(1000);  // 此线程要休眠 1 秒       
      }
      catch(InterruptedException e){/*...*/}
    }  
  }
 
  public static void main(String abc[])
  {
    Thread ThreadObj1 = new myDog();   
    ThreadObj1.start();     //  自动调用  run()
   
    Thread ThreadObj2 = new j02140301();   
    ThreadObj2.start();     //   自动调用  run()
   
   
    for(int x=1;x<=5;x++)// main thread 执行此 for 叙述句
    { 
     System.out.print("A ");
    }
    System.out.println();   
  } //到此 main thread 就停了
}

//=======================================================
//另一个继承 Thread 的类
class myDog extends Thread  // 步骤 1
{
  public void run()   // 步骤 2
  {
    System.out.print("dog ");  
  }
}


2、public class j02140302 implements Runnable  // 步骤 1
{
  public void run()   // 步骤 2
  {
    while(true)
    { 
      System.out.println("欢迎~~ ");
      //....
      try
      {
        Thread.sleep(1000);  // 休眠 1000 毫秒
      }
      catch(InterruptedException e){  }
    }  
  } 
 
  public static void main(String abc[])
  {   
    Thread ThreadObj1 = new Thread( new welcome() );   // 步骤 3 ,利用 Runnable 对象建构 Thread 对象
    ThreadObj1.start();     // 步骤 4   自动调用 welcome 实现的 run()
   
    Thread ThreadObj2 = new Thread( new j02140302() );   // 步骤 3 ,利用 Runnable 对象建构 Thread 对象
    ThreadObj2.start();     // 步骤 4   自动调用 j02140302 实现的 run()     
  }
}

class myFriend
{
  public void sayHello()
  {
    System.out.println("朋友!好久不见!");
  }
}

class welcome extends myFriend implements Runnable   // 步骤 1    
{             //拥有 myFriend 的实例,也有 Runnable 的实例                          
  public void run()   // 步骤 2
  { 
    while(true)
    {
      sayHello();
      try
      {
        Thread.sleep(3000);   // 休眠 3000 毫秒
      }
      catch(InterruptedException e){  }
    }
  } 
}

 

原创粉丝点击