您的位置:首页 > 其它

线程管理

2015-08-19 14:05 225 查看

1. 创建和运行线程

a. Extending Thread类,overriding run()方法;

b. 实现Runnable接口,创建一个Thread对象并传入实现Runnable的类的对象。

public class Calculator implements Runnable {
@Override
public void run() {

}
}

Thread thread = new Thread(new Calculator());
thread.start();


2. 获取/设置线程属性

thread.setPriority(Thread.MAX_PRIORITY);
thread.setName("Thread-0");

thread.getId();
thread.getName();
thread.getPriority();
thread.getState();

线程总有6种状态:new, runnable, blocked, waiting, time waiting or terminated.

3. 中断线程

thread.interrupt();

if(isInterrupted())
System.out.println("The current thread is interrupted!");

4. 控制线程的中断

@Override
public void run() {
try {
process();
} catch(InterruptedException e) {
System.out.printf("%s: has been interrupted", Thread.currentThread().getName());
}
}

private void process() throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
}



5. 休眠/恢复线程

try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
};
thread.interrupt();
当调用sleep()方法时,线程停止执行一段时间。在这段时间内是不消耗CPU时间的,因此CPU可以执行其他的task。

6. 等待线程的结束

try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
join()方法可以传入一个时间作为参数,表示等待指定的时间。

7. daemon线程

thread.setDaemon(true);
Java线程分为守护线程与普通用户线程,他们的区别是:java程序会在所有用户线程都执行完了才结束退出,即使主线程执行完了只要还有用户线程执行程序就在运行。但是如果其他用户线程全部执行完了守护线程如果没执行完的话它会自动被jvm终止,然后结束程序。

8. 处理UncaughtException

class ExceptionHandler implements UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
}
}

当一个线程发生了uncaught exception时, JVM会试着查找三种可能的Handler:

1) 该线程的uncaught exception handler

2) ThreadGroup的uncaught exception handler

3) 默认的uncaught exception handler

9. ThreadLocal对象

private static ThreadLocal<Date> startDate = new ThreadLocal<Date>() {
protected Date initialValue() {
return new Date();
}
}

10. 线程组

ThreadGroup Thread thread = new Thread(new ThreadGroup("group name"), new Thread())
线程组允许我们将多个线程看做一个单元,并提供对线程组中的线程对象的操作。

11. 处理线程组的UncaughtException

class MyThreadGroup extends ThreadGroup{
@Override
public void uncaughtException(Thread t, Throwable e) {
}
}

12. 通过线程工厂创建线程

class MyThreadFactory implements ThreadFactory {
@Override
public void newThread(Runnable e) {
}
}
使用工厂来创建新对象的优点:

1)容易修改被创建对象对应的类和创建对象的方法;

2)容易限制有限资源的对象的创建,例如某个类型只能有n个对象实例;

3)容易生成创建对象的统计数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: