zoukankan      html  css  js  c++  java
  • Java基础--多线程

    1.启动线程的注意事项

    无论何种方式,启动一个线程,就要给它一个名字!这对排错诊断
    系统监控有帮助。否则诊断问题时,无法直观知道某个线程的用途。

    启动线程的试:

    a.

    Thread thread = new Thread("thread name") {
    public void run() {
    // do xxx
    }
    };
    thread.start();

    b.

    public class MyThread extends Thread {
    public MyThread() {
    super("thread name");
    }
    public void run() {
    // do xxx
    }
    }
    MyThread thread = new MyThread ();
    thread.start();

    c.

    Thread thread = new Thread() {
    public void run() {
    // do xxx
    }
    };
    thread.setName("thread name");
    thread.start();

    d.

    Thread thread = new Thread(task); // 传入任务
    thread.setName(“thread name");
    thread.start();

    e.

    Thread thread = new Thread(task, “thread name");
    thread.start();

    2.要响应线程中断

    程序应该对线程中断作出恰当的响应。

    a.

    Thread thread = new Thread("interrupt test") {
    public void run() {
    for (;;) {
    doXXX();
    if (Thread.interrupted()) {
    break;
    }
    }
    }
    };
    thread.start();

    b.

    public void foo() throws InterruptedException {
    if (Thread.interrupted()) {
    throw new InterruptedException();
    }
    }

    c.

    Thread thread = new Thread("interrupt test") {
    public void run() {
    for (;;) {
    try {
    doXXX();
    } catch (InterruptedException e) {
    break;
    } catch (Exception e) {
    // handle Exception
    }
    }
    }
    };
    thread.start();

  • 相关阅读:
    泛型冒泡排序继承IComparable接口
    C#中枚举与位枚举的区别和使用
    C#中把二维数组转为一维数组
    一维数组的冒泡排序
    C#控制台的两个二维数组相加
    vs2019连接MySql的连接字符串
    Ajax方法请求WebService实现多级联动
    kafka-manager无法启动解决方法
    SQL优化————Insert
    读写锁
  • 原文地址:https://www.cnblogs.com/jasonboboblog/p/12783853.html
Copyright © 2011-2022 走看看