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            }         }     } }
复制代码

  b) 打印连续句子

复制代码
public class ThreadPrintDemo2 {     private char[] arr = new char[]{'a', ' ', 'b', 'c', 'd', 'e'};      public

                    
                
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信