首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

java 线程创办和比较

2013-10-30 
java线程创建和比较创建java 线程有两种方法:继承thread类或实现Runnable接口的重载run()方法1、继承Thread

java 线程创建和比较
创建java 线程有两种方法:继承thread类或实现Runnable接口的重载run()方法
1、继承Thread方法创建线程
    public class ThreadDemo extends Thread{
      private String address;
      private int tickets = 10;
      public ThreadDemo (String address){
          this.address = address;
      }
      public void run(){
          while(tickets > 0){
              System.out.println(address+"卖出:"+tickets--+"号票");
          }
      }
   }
2、实现Runnable接口创建线程
    public class RunnableDemo implements Runnable{
      private String address;
      private int tickets = 10;
      public RunnableDemo (){}

      public RunnableDemo (String address){
          this.address = address;
      }
      publicvoid run(){
          while(tickets > 0){
              System.out.println(address+"卖出:"+tickets--+"号票");
          }

      }
   }
3、执行
    public class Demo extends THread{
      public static void main(){
          //1、调用Thread
            ThreadDemo threadDemo1  = new ThreadDemo("窗口1");
            ThreadDemo threadDemo2  = new ThreadDemo("窗口2");
            ThreadDemo threadDemo3  = new ThreadDemo("窗口3");
            threadDemo1.start();
            threadDemo2.start();
            threadDemo3.start();
          //2、调用Runnable(非资源共享)
            RunnableDemo runnableDemo1 = new RunnableDemo("窗口1");
            RunnableDemo runnableDemo2 = new RunnableDemo("窗口2");
            RunnableDemo runnableDemo3 =new RunnableDemo("窗口3");
            Thread thread1 = new Thread(runnableDemo1);
            Thread thread2 = new Thread(runnableDemo2);
            Thread thread3 = new Thread(runnableDemo3);
            thread1.start();
            thread2.start();
            thread3.start();
          //3、资料共享只能调用Runnable
            RunnableDemo runnableDemo = new RunnableDemo("窗口1");
            Thread thread1 = new Thread(runnableDemo,"窗口1");
            Thread thread2 = new Thread(runnableDemo,"窗口2");
            Thread thread3 = new Thread(runnableDemo,"窗口3");
            thread1.start();
            thread2.start();
            thread3.start();

      }
   }

热点排行