在编程中,咱们常常使用多线程来提高性能,因此这就涉及到互斥和同步的问题了。而在编程中,咱们通常都是经过以下方式来完成多线程的互斥和同步:编程
在Linux C编程中,咱们一般使用pthread类库来完成跨平台的多线程控制,以下是几个经常使用的API:多线程
注意:**pthread类库是glibc(绝大多数Linux平台标准C库。)的一部分。这些功能都是经过中断号进入内核来完成的,而非仅仅作了Linux兼容API。**具体可见 glibc-2.23\sysdeps\nacl\nacl-interface-list.h ,声明wait(timeout)功能中断号文件。并发
在Java中,多线程的控制已是一个统一标准了,通常都是经过Java原生API或者JUC来实现并发控制。这里来讲说原生的API:app
经过这些API,咱们基本上能实现Java的多线程并发控制,固然了可使用最新的JUC并发库的API。而这些API底层也是能够经过pthread这个C库来实现。ide
Java中Timer的实现原理就是经过 wait 和 notify 以及 synchronized 来实现的:性能
Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { } }, 1000);
其实,Timer持有TimerImpl,其实Impl就是一个Thread实现,它一直阻塞等待task的到来,见run代码:this
public void run() { while (true) { TimerTask task; synchronized (this) { // need to check cancelled inside the synchronized block if (cancelled) { return; } //等待任务 if (tasks.isEmpty()) { if (finished) { return; } // no tasks scheduled -- sleep until any task appear try { //等待任务加入后,会经过notify来通知它能够运行 this.wait(); } catch (InterruptedException ignored) { } continue; } .... if (timeToSleep > 0) { // sleep! try { //延迟执行代码 this.wait(timeToSleep); } catch (InterruptedException ignored) { } continue; } // no sleep is necessary before launching the task ... } ... try { //具体执行任务 task.run(); taskCompletedNormally = true; } finally { ... } } }
能够看到TimerImpl的run代码会经过wait来阻塞等待任务加入queue,而后经过notify告知它能够运行task。timer#schedule最后会调用TimerImpl#insertTask,具体代码以下:线程
private void insertTask(TimerTask newTask) { // callers are synchronized tasks.insert(newTask); this.notify(); }
**因此任务加入队列后,经过notify来告知阻塞在等待任务的线程(TimerImpl#run)。**这样子就实现了Timer的功能了,而且经过wait(timeout)实现了delay的功能。code
多线程的控制,其实大多都是依赖:orm
这两种类型的API来完成并发控制。
而在此基础上,咱们能够实现各类各样的多线程并发控制,好比说:MQ,CountDownLatch等。