线程操作API

1.currentThread

2.getId() 、getName()、getPriority()、getStart、isAlive()、isDaemon()、isInterrupted()

3.setPriority()、

4.setDaemon()、

5、sleep()、

6、yield()、

7、join()、

8、interrupt()

---------------------------------------------------------------------

1. Thread.currentThread方法

Thread的静态方法currentThread方法可以用于获取运行当前代码片段的线程。
Thread current = Thread.currentThread();

 /**
* 获取当前代码块的线程
* @author Administrator
*
*/ class TestThreadDemo4{
public static void main(String[] args) {
/*
* 当程序运行起来时 Os 会启动一个进程来运行
* JVM ,而进程启动后会创建一个线程,用这个线程来运行Main方法
*/
//这里获取的是运行main方法的线程
Thread t =Thread.currentThread();
System.out.println("运行main方法的线程是:"+t); //main 方法中调用
testCurrent();
//创建线程
Thread t1 =new Thread(){
@Override
public void run() {
super.run();
System.out.println("运行T1线程是:"+Thread.currentThread());
testCurrent();
}
};
t1.start(); }
/**
* 输出调用当前方法的线程
*/
public static void testCurrent(){
System.out.println("运行testCurrendt方法的线程是:"+Thread.currentThread());
}
}

运行main方法的线程是:Thread[main,5,main]
运行testCurrendt方法的线程是:Thread[main,5,main]
运行T1线程是:Thread[Thread-0,5,main]
运行testCurrendt方法的线程是:Thread[Thread-0,5,main]

2. 获取线程信息

Thread提供了 获取线程信息的相关方法:

long getId():返回该线程的标识符 全局唯一的 不能重复
String getName():返回该线程的名称
int getPriority():返回线程的优先级
Thread.state getState():获取线程的状态
boolean isAlive():测试线程是否处于活动状态
boolean isDaemon():测试线程是否为守护线程
boolean isInterrupted():测试线程是否已经中断

 /**
* 获取线程信息的相关方法
* @author Administrator
*
*/
class TeatThreadDemo{
public static void main(String[] args) {
//获取调用main方法的线程
Thread main =Thread.currentThread();
System.out.println("ID:"+main.getId());
System.out.println("name:"+main.getName());
System.out.println("优先级:"+main.getPriority());
System.out.println("状态:"+ main.getState());
System.out.println("是否活动:"+ main.isAlive());
System.out.println("是否为守护进程"+ main.isDaemon());
System.out.println("是否被中断:"+main.isInterrupted());
}
}

3. 线程优先级

线程的切换是由线程调度控制的,我们无法通过代码来干涉,但是我们可以通过提高线程的优先级来最大程度的改善线程获取时间片的几率。
线程的优先级被划分为10级,值分别为1-10,其中1最低,10最高。线程提供了3个常量来表示最低,最高,以及默认优先级:
Thread.MIN_PRIORITY,
Thread.MAX_PRIORITY,
Thread.NORM_PRIORITY
设置优先级的方法为:
void setPriority(int priority)

 /**
* 线程优先级
* 线程优先级有10个级别 1-10
* 1最小,有常量对应 MIN_PRIORITY
* 10最大 有常量对应 MAX_PRIORITY
* 5为默认优先级 也有常量对应 NORM_PRIORITY
* 理论上优先级越高的线程获取时间片的册数越多
* @author Administrator
*
*/
public class TestThreadDemo6 {
public static void main(String[] args) {
Thread min =new Thread(){
@Override
public void run() { super.run();
for(int i=0;i<100;i++){
System.out.println("min");
}
}
};
Thread max =new Thread(){
@Override
public void run() { super.run();
for(int i=0;i<100;i++){
System.out.println("max");
}
}
};
Thread norm =new Thread(){
@Override
public void run() { super.run();
for(int i=0;i<100;i++){
System.out.println("norm");
}
}
};
min.setPriority(Thread.MIN_PRIORITY);
max.setPriority(Thread.MAX_PRIORITY);
min.start();
max.start();
norm.start();
}
}

4. 守护线程

守护线程与普通线程在表现上没有什么区别,我们只需要通过Thread提供的方法来设定即可:
void setDaemon(boolean )
当参数为true时该线程为守护线程。
守护线程的特点是,当进程中只剩下守护线程时,所有守护线程强制终止。
GC就是运行在一个守护线程上的。
需要注意的是,设置线程为后台线程要在该线程启动前设置。

GC就是运行在一个守护线程上的。
需要注意的是,设置线程为后台线程要在该线程启动前设置。
Thread daemonThread = new Thread();
daemonThread.setDaemon(true);
daemonThread.start();

/**
* 测试守护线程:前台线程和后台线程
* @author Administrator
*
*/
class TestDemo1{
public static void main(String[] args) {
/*
* rose 扮演者:前台线程
*
*/
Thread rose =new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++){
System.out.println("rose:let me go");
} System.out.println("rose:aaaaaaa");
System.out.println("音效:普通");
}
};
/*
* jack 是后台线程
*
*/
Thread jack =new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0;i<10;i++){
System.out.println("jack:you jump i jump!");
} System.out.println("jack:a弄弄哦aaaaaa");
System.out.println("音效:扑通!");
}
};
//将jack设置为后台线程
jack.setDaemon(true);
rose.start();
jack.start();
//加上这句话的效果
while(true);
}
}

5. sleep方法

Thread的静态方法sleep用于使当前线程进入阻塞状态:
static void sleep(long ms)
该方法会使当前线程进入阻塞状态指定毫秒,当指定毫秒阻塞后,当前线程会重新进入Runnable状态,等待分配时间片。
该方法声明抛出一个InterruptException。所以在使用该方法时需要捕获这个异常。

/**
* Sleep 阻塞
*
*/ class TestThreadDemo8{
public static void main(String[] args) {
//实现一个电子表功能
/*
* 每秒输出一下当前系统时间--> 11:12:55
* 1.创建SimpleDateFormate 指定时间格式
* 2.创建当前系统时间所对应Date对象
* 3.通过SimpleDateFormate的format方法将date转换为字符串
* 4.想实现电子表功能 就循环每隔1秒执行一次2,3步骤
*/
SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss");
while(true){
Date now =new Date();
System.out.println(sdf.format(now));
try {
Thread.sleep(1000); //每输出一次时间后阻塞1秒钟 } catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

注:该程序可能会出现"跳秒"现象,因为阻塞一秒后线程并非是立刻回到running状态,而是出于runnable状态,等待获取时间片。那么这段等待时间就是"误差"。所以以上程序并非严格意义上的每隔一秒钟执行一次输出。

6. yield方法

Thread的静态方法yield:
static void yield()
该方法用于使当前线程主动让出当次CPU时间片回到Runnable状态,等待分配时间片。
7. join方法

Thread的方法join:
void join()
该方法用于等待当前线程结束。此方法是一个阻塞方法。
该方法声明抛出InterruptException。

 /**
* join
* @author Administrator
*本身并发的线程是没有先后顺序的
*/ class TestThreadDemo23{
/*
* 图片是否下载完毕 这个写在main函数以外的原因 是因为
* run 局部函数调用 局部变量 需要final修饰 如果这样就没法修改
*/
private static boolean isfinish =false;
public static void main(String[] args) {
final Thread download =new Thread(){
@Override
public void run() {
super.run();
System.out.println("download: 开始下载图片");
for(int i=0;i<100;i++){
System.out.println("download:已经下载了%"+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isfinish =true;
System.out.println("下载完毕");
}
}; Thread show =new Thread(){
public void run() {
System.out.println("show:显示其他信息");
System.out.println("show:显示图片。。");
//这里应当等待download线程工作完毕
try{
download.join();
}catch(InterruptedException e){
e.printStackTrace();
}
if (!isfinish){
System.out.println("show: 显示图片失败");
}else{
System.out.println("show:图片显示完毕");
}
} };
download.start();
show.start();
}
}
8.interrupt()

进程中断异常

interrupt方法好多初学者会感到困惑,发现一些情况下并不能终止线程。在java API中有对此详细的说明:

如果线程在调用 Object 类的 wait()wait(long) 或 wait(long, int) 方法,或者该类的join()join(long)join(long, int)sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException

如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException

因此,可以看出,interrupt之后作用到 wait() join() 已经sleep()上


/**
* 进程中断异常
* @author Administrator
*
*/ class TestThreadDemo10{
public static void main(String[] args) {
/*
* 林永健 处于睡眠阻塞的线程
*/
final Thread lin =new Thread(){
@Override
public void run() {
super.run();
System.out.println("林:刚美完容,睡觉吧");
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("林:干嘛呢!干嘛呢");
}
}
}; /*
* 黄宏 用于中断程序的线程
*/
Thread huang =new Thread(){
@Override
public void run() {
System.out.println("黄:开始砸墙");
for(int i=0;i<10;i++){
System.out.println("黄:80");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("黄:搞定");
lin.interrupt(); //中断lin这个线程
}
};
lin.start();
huang.start();
}
}

线程操作API的更多相关文章

  1. iOS子线程操作UI问题检查

    iOS开发中,因为大部分函数都不是线程安全的,所以UI子线程中操作UI是非常危险的事,但是有时候因为开发者经验不足,不知道子线程中不能UI,或者知道但是写代码的时候没注意,或者不知道那些函数操作UI了 ...

  2. HTML5文件操作API

    HTML5文件操作API       一.文件操作API 在之前我们操作本地文件都是使用flash.silverlight或者第三方的activeX插件等技术,由于使用了这些技术后就很难进行跨平台.或 ...

  3. 线程属性API

    数据类型:pthread_attr_t 操作API: // 初始化线程属性 int pthread_attr_init(pthread_attr_t *attr);// 初始化为系统支持的所有属性的默 ...

  4. 线程同步API及它们的属性

    头文件:<pthread.h> 编译记得加 -lpthread库 1:互斥锁(mutex) 1.1:互斥锁API 数据类型:pthread_mutex_t // 初始化一个互斥锁 int ...

  5. 线程池 API (转)

    文档原始地址    目录 线程池概述 线程池对象 回调环境对象 工作对象 等待对象 计时器对象 I/O 完成对象 使用清理组简化清理 回调实例 API    随着 Windows Vista® 的发布 ...

  6. Html5 学习系列(四)文件操作API

    原文:Html5 学习系列(四)文件操作API 引言 在之前我们操作本地文件都是使用flash.silverlight或者第三方的activeX插件等技术,由于使用了这些技术后就很难进行跨平台.或者跨 ...

  7. winform 跨线程操作控件

    当进行winform的开发时,经常遇到用时比较久的操作,在传统的单线程程序中,用户必须等待这个耗时操作完成以后才能进行下一步的操作,这个时候,多线程编程就派上用场了,将这个耗时的操作放到一个新的子线程 ...

  8. 扩展BindingList,防止增加、删除项时自动更新界面而不出现“跨线程操作界面控件 corss thread operation”异常

    在做界面程序时,常常需要一些数据类,界面元素通过绑定等方式显示出数据,然而由于UI线程不是线程安全的,一般都需要通过Invoke等方式来调用界面控件.但对于数据绑定bindingList而言,没法响应 ...

  9. WinForm中新开一个线程操作 窗体上的控件(跨线程操作控件)

    最近在做一个winform的小软件(抢票的...).登录窗体要从远程web页面获取一些数据,为了不阻塞登录窗体的显示,开了一个线程去加载数据远程的数据,会报一个错误"线程间操作无效: 从不是 ...

随机推荐

  1. Html类ImageGetter接口

    public class ImgLabelActivity extends Activity { private static final String TAG = "ImgLabelAct ...

  2. rlwrap(在sqlplus下使用上下键)

    一:安装readline OS的安装光盘里提供了readline包. # RHEL 4 [root@oracle11g ~]# rpm -Uvh readline* error: Failed dep ...

  3. 初探接口测试框架--python系列7

    点击标题下「蓝色微信名」可快速关注 坚持的是分享,搬运的是知识,图的是大家的进步,没有收费的培训,没有虚度的吹水,喜欢就关注.转发(免费帮助更多伙伴)等来交流,想了解的知识请留言,给你带来更多价值,是 ...

  4. 使用Donut Caching和Donut Hole Caching在ASP.NET MVC应用中缓存页面

    Donut Caching是缓存除了部分内容以外的整个页面的最好的方式,在它出现之前,我们使用"输出缓存"来缓存整个页面. 何时使用Donut Caching 假设你有一个应用程序 ...

  5. 了解Entity Framework中事务处理

    Entity Framework 6以前,框架本身并没有提供显式的事务处理方案,在EF6中提供了事务处理的API. 所有版本的EF,只要你调用SaveChanges方法进行插入.修改或删除,EF框架会 ...

  6. com组件 智能指针崩溃问题崩溃问题

    int main(){ CoInitialize(NULL); HRESULT hr; IWinHttpRequestPtr pHttpReq=NULL; pHttpReq.CreateInstanc ...

  7. CSS常用布局整理(二)

    1-2-1单列变宽布局 side列定宽300px,content列变宽,尺寸是100%-300px.核心的问题就是浮动列的宽度应该等于“100% - 300px”,而CSS显然不支持这种带有减法运算的 ...

  8. Belkasoft Evidence Center could handle Chinese characters well

    I've been using Belkasoft Evidence Center for a very long time. It could handle Chinese characters w ...

  9. Linux命令之type

    1:linux命令可以分为很多类,其中常见得类型: (1):builtin --内置命令 (2):alias --命令别名 (3):file --外部命令 具体有哪些内置命令以及内置命令各个用法: [ ...

  10. hosts文件导致打不开某些网站

    如果出现,某些网站访问不了,公司也没有进行限制的情况下,考虑是hosts文件出问题了. 解决办法:删除hosts文件,新建一个同名文件.