java线程之创建线程类
1.extends Thread方法
1 class Person extends Thread { 2 int sum1 = 50; 3 4 // 含参构造器 5 public Person(String name) { 6 super(name); 7 } 8 9 // 重写run()方法 10 @Override 11 public void run() { 12 for (int i = 0; i < 50; i++) { 13 eat(); 14 } 15 } 16 17 // 线程具体任务 18 public void eat() { 19 if (sum1 > 0) { 20 System.out.println(getName() + "吃了一个苹果," + "还剩" + --sum1 + "个苹果"); 21 try { 22 Thread.sleep(100); //休眠100ms 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 } 27 } 28 } 29 30 public class Eatapple { 31 //创建线程对象,并开启 32 public static void main(String[] args) { 33 Person x = new Person("x"); 34 x.start(); 35 } 36 }
控制台输出(截取部分)
1 x吃了一个苹果,还剩49个苹果 2 x吃了一个苹果,还剩48个苹果 3 x吃了一个苹果,还剩47个苹果 4 x吃了一个苹果,还剩46个苹果 5 x吃了一个苹果,还剩45个苹果 6 x吃了一个苹果,还剩44个苹果 7 x吃了一个苹果,还剩43个苹果 8 x吃了一个苹果,还剩42个苹果 9 x吃了一个苹果,还剩41个苹果 10 x吃了一个苹果,还剩40个苹果 11 x吃了一个苹果,还剩39个苹果 12 x吃了一个苹果,还剩38个苹果
上面红字标出的getName(),实际上等价于this.getName(),返回当前线程的名称,在这里就是“x”。
Thread.sleep(100);线程休眠100ms,所以控制台会逐条打印语句。
2.implements Runnable 方法
1 class Apple implements Runnable { 2 int sum1 = 50; 3 4 // 重写run()方法 5 @Override 6 public void run() { 7 for (int i = 0; i < 50; i++) { 8 eat(); 9 } 10 } 11 12 // 线程具体任务 13 public void eat() { 14 if (sum1 > 0) { 15 System.out.println(Thread.currentThread().getName() + "吃了一个苹果," + "还剩" + --sum1 + "个苹果"); 16 try { 17 Thread.sleep(100); 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 } 22 } 23 } 24 25 public class Eatapple { 26 public static void main(String[] args) { 27 //创建线程对象并开启 28 Apple a = new Apple(); 29 new Thread(a, "AA").start(); 30 } 31 }
注意这里获取线程名称“AA”的方法。
解析:extends Thread方法看上去清晰明了,新建一个子类继承线程类,实例化子类对象(线程对象),start()
方法开启线程。
implements Runnable方法,实现了一个Runnable接口,然后用Thread(Runnable class,String name)构造
方法新建线程,start()方法开启。
在多线程操作中,由于第一种方法创建的线程不能够完全实现资源以及信息的的共享,所以我们建议使用第二种方法。
(我不怕千万人阻挡,只怕自己投降!)