疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

创建线程的两个方式


 

   

  方式一:

  package com.Thread1;

  public class myRunable implements Runnable {

  public int count;

  @Override

  public void run() {

  while (count < 100) {

  count++;

  System.out.println("count:" + count + "由"

  + Thread.currentThread().getName() + "创建");

  }

  }

  }

  package com.Thread1;

  public class myRunableTest {

  public static void main(String[] args) {

  Thread t1 = new Thread(new myRunable(), "线程1");

  t1.start();

  Thread t2 = new Thread(new myRunable(), "线程2");

  t2.start();

  }

  }

  方式二:

  package com.Thread1;

  public class MyThread1 extends Thread {

  public int count;

  @Override

  public void run() {

  while (count <100) {

  count++;

  System.out.println("count:"+count+"由"+Thread.currentThread().getName()+"创建");

  }

  }

  }

  package com.Thread1;

  public class MyThread1Test {

  public static void main(String[] args) {

  // MyThread1 mt1 = new MyThread1();

  // Thread t = new Thread(mt1);

  // t.start();

  Thread t1 = new MyThread1();

  t1.setName("线程1");

  t1.start();

  Thread t2 = new MyThread1();

  t2.setName("线程2");

  t2.start();

  }

  }