A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 迷途老马 中级黑马   /  2015-10-20 23:22  /  375 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1. 通过扩展 Thread 类来创建多线程:

public class MutliThreadDemo {
     public static void main(String[] args) {
         MutliThread m1=new MutliThread("Window 1");
        MutliThread m2=new MutliThread("Window 2");
        MutliThread m3=new MutliThread("Window 3");
         m1.start();
        m2.start();
          m3.start();
   }
}

public class MutliThread extends Thread {
     private int ticket=100;//每个线程都拥有100张票

     public MutliThread (){}
      public MutliThread (String name){
        super(name);
     }
   
     @Override
     public void run() {
        while(ticket>0){
             System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
         }
   }
}

2. 通过实现 Runnable 接口来创建多线程:
public class MutliThreadDemo {
    public static void main(String[] args) {
         MutliThread m1=new MutliThread("Window 1");
        MutliThread m2=new MutliThread("Window 2");
        MutliThread m3=new MutliThread("Window 3");
        Thread t1=new Thread(m1);
         Thread t2=new Thread(m2);
        Thread t3=new Thread(m3);
        t1.start();
        t2.start();
         t3.start();
     }
}

public class MutliThread implements Runnable{
     private int ticket=100;//每个线程都拥有100张票
     private String name;
    MutliThread(String name){
         this.name=name;
     }
     public void run(){
        while(ticket>0){
             System.out.println(ticket--+" is saled by "+name);
        }
     }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马