java新建线程有三种方式
1.实现Runnable接口.
2.继承Thread类,Thread类本身也是实现了Runnable接口的,继承了Thread类之后需要重写run方法
3.实现Callable接口,FutureTask构造里需要Callable参数,实现call后,get()方法可拿到返回值,get()方法是阻塞的(后面介绍).FutureTask本身也是实现了Runnable接口
1和2比较常见,分析下3
public static volatile int b;
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> future = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Thread.sleep(1000);
return 1;
}
});
Thread thread = new Thread(future);
thread.start();
long start = System.currentTimeMillis();
b = future.get();
long end = System.currentTimeMillis();
System.out.println("b:" + b + "--阻塞了:" + (end - start) + "ms");
}
打印结果
b:1--阻塞了:1001ms
关于get()方法的阻塞,我们看看get()方法下的awaitDone
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
get()方法在循环里检查到还没有拿到返回值的状态下会使该线程进入等待状态
LockSupport.park(this);这个方法效果类似于wait(),
LockSupport.unpark(thread)效果类似于notify();
我们可以在刚才的代码里尝试使用下
public static volatile int b;
public static void main(String[] args) throws ExecutionException, InterruptedException {
Object object = new Object();
FutureTask<Integer> future = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// Thread.sleep(1000);
LockSupport.park(this);
return 1;
}
});
Thread thread = new Thread(future);
thread.start();
long start = System.currentTimeMillis();
new Thread(()->{
try {
Thread.sleep(1000);
LockSupport.unpark(thread);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
b = future.get();
long end = System.currentTimeMillis();
System.out.println("b:" + b + "--阻塞了:" + (end - start) + "ms");
}
打印结果
b:1--阻塞了:1032ms
这里thread线程里使用了park();然后在另一个线程里休眠1s后去unpark()之前的thread,get()方法就在1s后拿到了返回值,我们可以用wait()和notify()也试试
public static volatile int b;
public static void main(String[] args) throws ExecutionException, InterruptedException {
Object object = new Object();
FutureTask<Integer> future = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// Thread.sleep(1000);
// LockSupport.park(this);
synchronized (object) {
object.wait();
}
return 1;
}
});
Thread thread = new Thread(future);
thread.start();
long start = System.currentTimeMillis();
new Thread(()->{
try {
Thread.sleep(1000);
// LockSupport.unpark(thread);
synchronized (object) {
object.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
b = future.get();
long end = System.currentTimeMillis();
System.out.println("b:" + b + "--阻塞了:" + (end - start) + "ms");
}
同样也是1s后get()方法拿到了返回值.
Callable可以在我们需要返回值之前做其他的事情.查看FutureTask源码我们可以看到FutureTask也是需要实现Runnable接口的,run()方法里面去执行我们实现的call方法拿返回值
run()方法里的call()执行成功之后CAS操作把FutureTask对象里的NEW状态修改为COMPLETING状态,然后返回值赋值给outcome,然后状态再置为NORMAL,接着唤醒get()里的阻塞,最后get()方法就能拿到值了
涉及的CAS操作还有线程的等待和唤醒还有各个并发工具类是研究各种源码时经常看到的东西,后面会详细讲解
线程的常用方法和线程的五个状态关系图
notify(),wait()都是Object里的方法,刚刚我们使用过;
interrupt()是去中断一个线程,并不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定.
yield()的作用是让步.它能让当前线程由“运行状态”进入到“就绪状态”,从而让其它具有相同优先级的等待线程获取执行权;但是,并不能保证在当前线程调用yield()之后,其它具有相同优先级的线程就一定能获得执行权;也有可能是当前线程又进入到“运行状态”继续运行!
join()方法会用在这样的场景,线程A,执行了线程B的join方法,线程A必须要等待B执行完成了以后,线程A才能继续自己的工作 ,写个例子让线程看起来有序执行.
static class JumpQueue implements Runnable {
private Thread thread;//用来插队的线程
public JumpQueue(Thread thread) {
this.thread = thread;
}
public void run() {
try {
System.out.println(thread.getName() + " will be join before "+ Thread.currentThread().getName());
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " terminated");
}
}
public static void main(String[] args) throws Exception {
Thread previous = Thread.currentThread();//现在是主线程
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new JumpQueue(previous), String.valueOf(i));
thread.start();
previous = thread;//赋值为前一个线程
}
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " terminated");
}
打印结果为
0 will be join before 1
main will be join before 0
1 will be join before 2
3 will be join before 4
2 will be join before 3
main terminated
0 terminated
1 terminated
2 terminated
3 terminated
4 terminated