java简单的多线程实现

来源:互联网 发布:visio 软件架构 编辑:程序博客网 时间:2024/05/17 08:40
thread类
  1. package hu.th;  
  2.   
  3. public class MyThread {  
  4.       
  5.     public MyThread(){  
  6.         new MyTh().start();  
  7.         new MyTh().start();  
  8.         new MyTh().start();  
  9.     }  
  10.       
  11.     public static void main(String[] args) {  
  12.         new MyThread();  
  13.     }  
  14.       
  15.     class MyTh extends Thread{  
  16.   
  17.         @Override  
  18.         public void run() {  
  19.                 for(int i=0;i<100;i++){  
  20.                     System.out.println(Thread.currentThread().getName()+"--"+i);  
  21.                     try {  
  22.                         Thread.sleep(100);  
  23.                     } catch (InterruptedException e) {  
  24.                         e.printStackTrace();  
  25.                     }  
  26.                 }  
  27.         }  
  28.           
  29.     }  
  30.   
  31. }  

Runnable接口



  1. package hu.th;  
  2.   
  3. public class MyThread {  
  4.       
  5.     public MyThread(){  
  6.         new Thread(new MyRun()).start();  
  7.         new Thread(new MyRun()).start();  
  8.         new Thread(new MyRun()).start();  
  9.     }  
  10.       
  11.     public static void main(String[] args) {  
  12.         new MyThread();  
  13.     }  
  14.       
  15.     class MyRun implements Runnable{  
  16.   
  17.         @Override  
  18.         public void run() {  
  19.             for(int i=0;i<100;i++){  
  20.                 System.out.println(Thread.currentThread().getName()+"--"+i);  
  21.                 try {  
  22.                     Thread.sleep(100);  
  23.                 } catch (InterruptedException e) {  
  24.                     e.printStackTrace();  
  25.                 }  
  26.             }  
  27.               
  28.         }  
  29.           
  30.     }  
  31.   
  32. }  

0 0