Java线程入门第二篇

Java线程通信方法

0、(why)每个线程都有自己的栈空间,我们要线程之间进行交流,合作共赢。

1、synchronized和volatile关键字

  a)  看下面的synchronized关键字

  b)  看下面的volatile关键字

2、等待/通知机制:一个线程A调用对象的wait()方法,另一个线程调用线程B的notity()或者的notifyall()方法.

  a)  顺序打印奇数偶数

public class ThreadPrintDemo2 { public static void main(String[] args) { final ThreadPrintDemo2 demo2 = new ThreadPrintDemo2(); //java8新特性 Thread t1 = new Thread(demo2 :: print1); Thread t2 = new Thread(demo2 :: print2); t1.start(); t2.start(); } public synchronized void print2() { for (int i = 1; i <= 100; i +=2) { System.out.println(i); this.notify(); //通知等待中的进程 try { this.wait(); //线程进入等待 Thread.sleep(100);// 防止打印速度过快导致混乱 } catch (InterruptedException e) { // NO } } } public synchronized void print1() { for (int i = 0; i <= 100; i += 2) { System.out.println(i); this.notify(); //通知等待中的进程 try { this.wait(); //线程进入等待 Thread.sleep(100);// 防止打印速度过快导致混乱 } catch (InterruptedException e) { // NO } } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zysgdj.html