读书也要记:Java 线程(基础)

2017-03-12  本文已影响78人  鸣鸣那只羊

近来读了好几篇“老马说编程”写的 Java 多线程文章,这里记录一下第一篇的摘要,以及拓展查找了点相关的东西,算是复习巩固(有些冷知识平时还真没留意过)。原文:(65) 线程的基本概念 / 计算机程序的思维逻辑

在 Java 中创建线程有两种方式,一种是继承 Thread,另外一种是实现 Runnable 接口。

extends Thread
/**
     * Returns a reference to the currently executing thread object.
     * @return  the currently executing thread.
     */
    public static native Thread currentThread();

难得看到 native 关键字,所以 Thread 是 JNI (Java Native Interface),略懵逼,哪位高人来指导下?

    /* For generating thread ID */
    private static long threadSeqNumber;
    private static synchronized long nextThreadID() {
        return ++threadSeqNumber;
    }

    /* For autonumbering anonymous threads. */
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }
    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
implements Runnable
程序什么时候退出,关于 daemon 线程
关于 Thread 的小知识
public static void main(String[] args) throws InterruptedException {
    Thread thread = new HelloThread();
    thread.start();
    thread.join();
}  

stop() 会引起线程涉及的 monitor 状态的不确定性,所以不建议被调用,那么怎么 stop 一个 Thread 啊,懵逼了吧。

The Answer: In Java there's no clean, quick or reliable way to stop a thread.
Instead, Threads rely on a cooperative mechanism called Interruption. This means that Threads could only signal other threads to stop, not force them to stop.

public class Task implements Runnable {
    private volatile boolean isRunning = true;

    public void run() {
        while (isRunning) {
            //do work
        }
    }

    public void kill() {
        isRunning = false;
    }
}
public class Task1 implements Runnable {
  public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                      // do work
           }
    }
}
// in other thread, call interrupt()
myThread.interrupt();

新加坡的“南京大排档”
上一篇 下一篇

猜你喜欢

热点阅读