关于线程2

2.1 线程定义和创建2:实现Runnable接口

【示例2】使用多线程实现龟兔赛跑2

public class TortoiseRunnable implements  Runnable {
    //private int num = 100;
    /**
     * 线程体,线程要执行的任务
     */
    @Override
    public void run() {
        while(true){
            while(true){
                System.out.println("乌龟领先了,加油...."+
                        Thread.currentThread().getName()+"   "+
                        Thread.currentThread().getPriority());
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        //创建乌龟线程对象
        //Runnable runnable = new TortoiseRunnable();
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                while(true){
                    System.out.println("乌龟领先了............"

+Thread.currentThread().getName());
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        //启动乌龟线程
        thread1.start();

        Thread thread2 = new Thread(runnable);
        thread2.start();
        while(true){
            System.out.println("兔子领先了,add oil ...."+
                    Thread.currentThread().getName()+"   "+
                    Thread.currentThread().getPriority());
        }
    }
}

两种方式的优缺点
   方式1:继承Thread类
   缺点:Java单继承,无法继承其他类
   优点:代码稍微简单
   方式2:实现Runnable接口
   优点  还可以去继承其他类 便于多个线程共享同一个资源

    • 缺点:代码略有繁琐
         实际开发中,方式2使用更多一些
    • 可以使用匿名内部类来创建线程对象
    • 已经学习的线程Thread的属性和方法

字段摘要

static int

MAX_PRIORITY 
          线程可以具有的最高优先级。

static int

MIN_PRIORITY 
          线程可以具有的最低优先级。

static int

NORM_PRIORITY 
          分配给线程的默认优先级。

方法摘要

static Thread

currentThread() 
          返回对当前正在执行的线程对象的引用。

 String

getName() 
          返回该线程的名称。

 int

getPriority() 
          返回线程的优先级。

 void

run() 
          如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回。

 void

setName(String name) 
          改变线程名称,使之与参数 name 相同。

 void

setPriority(int newPriority) 
          更改线程的优先级。

 void

setPriority(int newPriority) 
          更改线程的优先级。

 void

start() 
          使该线程开始执行;Java 虚拟机调用该线程的 run 方法。

原文地址:https://www.cnblogs.com/vincentmax/p/14245948.html