Java基础知识学习(六)

多线程

先了解线程的概念

多线程需要注意的地方

优先级、线程同步、消息传递、数据共享、死锁等

Java线程类 Thread,实现接口 Runnable

Thread常用方法

getName 获得线程名称
getPriority 获得线程优先级
jsAlive 判定线程是否仍在运行
join 等待一个线程终止
run 线程的入口点.
sleep 在一段时间内挂起线程
start 通过调用运行方法来启动线程

一个线程的例子,当Java程序启动时,一个线程立刻运行,该线程通常叫做程序的主线程,它是产生其他子线程的线程;通常它必须最后完成执行,因为它执行各种关闭动作。

   public static void main(String[] args) {
        Thread t = Thread.currentThread();
        System.out.println("Current thread: " + t);
        t.setName("My Thread");
        System.out.println("After name change: " + t);

        try {
            for (int n = 5; n > 0; n--) {
                System.out.println(n);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }
    }

创建线程

实例化一个Thread对象来创建一个线程。Java定义了两种方式:

  • 实现Runnable 接口;
  • 可以继承Thread类。

创建线程的最简单的方法就是创建一个实现Runnable 接口的类,实现run()方法

class NewThread implements Runnable {
    Thread t;

    NewThread() {
        t = new Thread(this, "Demo New Thread");
        t.start();
    }

    public void run() {for (int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                Thread.sleep(500);
            }
    }
}

创建线程的另一个途径是创建一个新类来扩展Thread类,然后创建该类的实例。

class NewThread extends Thread {
    NewThread() {
        super("Demo Thread");
        start();
    }
    public void run() {
            for(int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                Thread.sleep(500);
            }
    }
}

创建多线程

public static void main(String[] args) {
    new NewThread();
    new NewThread();
    new NewThread();
    System.out.println("Main thread exiting.");
}

使用多线程要理解 join()方法,主线程会等待子线程结束在继续执行

つづけ

原文地址:https://www.cnblogs.com/alex09/p/4885281.html