线程
定义: 线程是进程中系统进行调度的最小执行单元
使用:
创建线程的两种方式:
- 继承Thread类,重写run()方法
- 实现Runnable接口,实现run()方法
创建线程类对象
Thread td1 = new MyThread(); //Thread的子类
启动线程:td1.start();
Thread td1 = new Thread(new RunnableImpl());
创建获取执行结果的线程
使用Callable接口和futureTask类
实现Callable接口,使用FutureTask包装,再作为参数传入Thread构造方法
public class CallableImpl implements java.util.concurrent.Callable<String> {
@Override
public String call() throws Exception {
Thread cuThread = Thread.currentThread();
for(int i=0;i<100;i++) {
System.out.println("线程名:"+cuThread.getName()+"id:"+cuThread.getId());
}
return cuThread.getName();
}
}
FutureTask<String> futureTask = new FutureTask<>(new CallableImpl());
//开启线程
new Thread(futureTask).start();
String strRes;
try {
strRes = futureTask.get();
System.out.println("返回的结果是:"+strRes);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
线程状态:
NEW ,新建
RUNNABLE, 可运行
BLOCKED, 阻塞
WAITING, 等待
TIMED_WAITING,定时等待
TERMINATED 终止
常用线程控制方法
设置线程的优先级: final void setPriority(int)
1-10的整数值,值越大优先级越高
ThreadTest threadTest = new ThreadTest();
threadTest.setPriority(10);
Thread thread = new Thread(new RunnableImpl());
thread.setPriority(1);
thread.run();
threadTest.start();
设置守护线程: final setDaemon(boolean)(true表示设置为守护线程)
守护线程: 为其它线程提供服务、随着用户线程终止而终止的线程
休眠:static native sleep(long)
Thread.sleep(1000);
联结线程: final join( ) ** final join(long )
- 当前线程进入等待状态,等待加入的线程终止
- 当前线程进入等待状态,等待加入的线程终止或指定时长结束
- 在一个线程中调用另一个线程的join()方法,当前线程会进入等待状态,等待join进来的线程终止(例如:在main方法中thread1使用join()方法,main进入等待状态)
中断线程: interrupt( )
向线程发出中断请求
该方法仅设置线程的中断状态,并不中断线程的运行!
true表示查询完就清除中断标志
线程礼让: static native yield( )
当前线程让出执行权,以允许具有相同优先级的其它线程获得运行机会
正确用法:
Thread.yield();