创建线程方法
//1
public static void main(String[] args) {
Thread thread=new mythread();
thread.start();
}
static class mythread extends Thread{
public void run(){
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
}
}
//2
public static void main(String[] args) {
mythread t1=new mythread();
Thread thread=new Thread(t1);
thread.start();
}
static class mythread implements Runnable{
public void run(){
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
}
}
//3
public static void main(String[] args) {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
}
});
thread.start();
}
//4
public static void main(String[] args) {
Thread thread=new Thread(()-> {
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
});
thread.start();
}
//5
public static void main(String[] args) {
Thread thread=new Thread(){
public void run(){
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
}
};
thread.start();
//6
public static void main(String[] args) {
FutureTask<Integer> task=new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
return null;
}
});
Thread thread=new Thread(task);
thread.start();
}
//7
public static void main(String[] args) throws ExecutionException, InterruptedException {
mycallable t1=new mycallable();
FutureTask<Integer> task=new FutureTask<>(t1);
Thread thread=new Thread(task);
thread.start();
System.out.println(task.get());
}
static class mycallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread t1=Thread.currentThread();
System.out.println(t1.getName());
return 1;
}
}
Thread() 创建线程对象
Thread(String name) 创建线程对象,并命名
Thread(Runnable target) 用Runnable创建线程对象
Thread(Runnable target,String name) 用Runnable创建线程对象,并命名
Thread(ThreadGroup group,Runnable target)线程分组
getId() 获取线程ID
getName() 获取线程名称
getState() 获取线程状态 线程状态共有6种1.NEW(新建状态)2.RUNNABLE(运行状态)3.BLOCKED(阻塞状态)4.WAITING(等待状态,无限期等待)5.TIMED_WAITING(有明确结束时间的等待)6.TERMINATED(销毁状态)
getPriority() 获取线程优先级 优先级最大为10,最小为1,默认优先级为5,优先级越高获取到CPU时间片的概率越高,因此一般会先执行完。
isDaemon() 是否守护线程 守护线程在用户线程执行完的时候也会结束,无论它是否执行完毕。守护线程中创建的线程默认是守护线程,守护线程不能在start()之后设置。
setDaemon(true) 设置为守护线程
isAlive() 是否存活
interrupted() (会清除标志位,是静态方法)
isInterrupted() 是否被中断(不会清除标志位)
interrupt() 中断线程
join() 等待线程结束再继续执行
join(long millis) 等待线程结束,最多等millis毫秒
join(long millis,int nanos)同理,但可以更高精度
public static Thread currentThread(); 返回当前线程对象的引用
yield() 让出CPU执行权
sleep(long millis) 休眠线程
TimeUnit.DAYS.sleep(1);//天
TimeUnit.HOURS.sleep(1);//小时
TimeUnit.MINUTES.sleep(1);//分
TimeUnit.SECONDS.sleep(1);//秒
TimeUnit.MILLISECONDS.sleep(1000);//毫秒
TimeUnit.MICROSECONDS.sleep(1000);//微妙
TimeUnit.NANOSECONDS.sleep(1000);//纳秒
线程不安全元素:①抢占式执行
②多个线程修改同一个变量
③非原子性操作
④内存可⻅性
⑤指令重排序