JAVA线程

01、基本概念:程序、进程、线程

  • 程序(program):为完成特定任务、用某种语言编写的一组指令的集合。即指一段静态的代码,静态对象。
  • 进程(process):程序的一次执行过程,或是正在运行的一个程序。是一个动态的过程:有它自身的产生、存在和消亡的过程----生命周期
    • 如:运行中的QQ,运行中的MP3播放器程序是静态的,进程是动态的
    • 进程作为资源分配的单位,系统在运行时会为每个进程分配不同的内存区域
  • 线程(Thread),进程可进一步细化为线程,是一个程序内部的一条执行路径
    • 若一个进程同一时间并行执行多个线程,就是支持多线程的
    • 线程是调度和执行的单位,每个线程拥有独立运行的运行栈和程序计数器(PC),线程切换的开销小。
    • 一个进程中的多个线程相同的内存单元/内存地址空间----->它们从同一堆中分配对象,可以访问相同的变量和对象。这就使得线程间通信更简便

单核CPU和多核CPU

单核CPU,其实是一种假的多线程,因为在一个时间单元内,也只能执行一个线程的任务,例如:虽然有很多车道,但是收费站只有一个工作人员在收费,只有收了费才能通过,那么CPU就好比收费人员。如果有个人不想交钱,那么收费人员可以把他“挂起”。但是因为CPU时间单元特别短,所以无法察觉。

如果是多核CPU,才能更好的发挥多线程的效率。(现在的服务器都是多核的)

一个JAVA应用程序java.exe,其实至少有三个线程:main()主线程、gc()垃圾回收线程、异常处理线程。当然如果发生异常,会影响主线程。

并行与并发

并行:多个CPU同时执行多个任务。

并发:一个CPU(采用时间片)同时执行多个任务。

使用多线程的优点

多线程程序的优点

  1. 提高应用程序的响应。对图形化界面更有意义,可增强用户体验
  2. 提高计算机系统的CPU的利用率
  3. 改善程序结构。将长而复杂的进程分为多个线程,独立运行,利于理解和修改

02、线程的创建和使用

2.1 线程的创建和启动

Java语言的JVM允许程序运行多个线程,它通过java.lang.Thread类来体现。

Thread类的特性

  • 每个线程都是通过某个特定Thread对象的run()方法来完成这个操作,经常把run()方法的主体成为线程体

  • 通过该Thread对象的start()方法来启动这个线程,而非直接调用run()

2.2 Thread类

  • Thread():创建新的Thread对象

  • Thread(String threadname):创建线程并指定线程实例名

  • Thread(Runnable target):指定创建线程的目标对象,它实现了Runnable接口中的run方法

  • Thread(Runnable target,String name):创建新的Thread对象

2.3 API中的创建进程的两种方式

JDK1.5之前创建执行线程的两种方法:

  • 继承Thread类的方法
  • 实现Runnable接口的方法
2.3.1 创建多线程的方式一:继承Thread类的方法

MyThread.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.company;
 
//1、创建一个继承Thread类的子类
class MyThread extends Thread{
    //2、重写Thread类的run()
    @Override
    public void run() {
        for(int count=1;count<100;count++){
            if(count%=2){
                System.out.println(count);
            }
        }
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        // 3、创建Thread的子对象
        MyThread thread1=new MyThread();
 
        // 4、通过此对象调用start():1、启动当前进程2、调用当前进程的run()
        thread1.start();
 
        //如下操作仍在main线程中进行
        for(int count=1;count<100;count++){
            if(count%2==0){
                System.out.println(count+"************main()******");
            }
        }
    }
}

 运行结果如下:

 子进程创建与执行过程

 

 

 

2.3.2 创建过程中的两个问题说明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.company;
 
//1、创建一个继承Thread类的子类
class MyThread extends Thread{
    //2、重写Thread类的run()
    @Override
    public void run() {
        for(int count=1;count<10;count++){
            if(count==2){
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
        }
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        // 3、创建Thread的子对象
        MyThread thread1=new MyThread();
 
        // 4、通过此对象调用start():1、启动当前进程2、调用当前进程的run()
        thread1.start();
 
        MyThread thread2=new MyThread();
        thread2.start();
 
        //如下操作仍在main线程中进行
        for(int count=1;count<10;count++){
            if(count%2==0){
                System.out.println(Thread.currentThread().getName()+":"+count+"************main()******");
            }
        }
    }
}

 启动两个线程的

写法一:

MyThread.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.company;
 
//1、创建一个继承Thread类的子类
class MyThread extends Thread{
    //2、重写Thread类的run()
    @Override
    public void run() {
        for(int count=1;count<10;count++){
            if(count%2==0){
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
        }
    }
}
class  MyThread2 extends Thread{
    @Override
    public void run() {
        for(int count=0;count<10;count++){
            if(count%2==0){
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
        }
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        // 3、创建Thread的子对象
        MyThread thread1=new MyThread();
 
        // 4、通过此对象调用start():1、启动当前进程2、调用当前进程的run()
        thread1.start();
 
        MyThread2 myThread2 = new MyThread2();
        myThread2.start();
    }
}

 写法二:

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.company;
 
public class Main {
 
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                for(int count=0;count<10;count++){
                    if(count%2==0){
                        System.out.println(Thread.currentThread().getName()+":"+count);
                    }
                }
            }
        }.start();
 
        new Thread(){
            @Override
            public void run() {
                for(int count=0;count<10;count++){
                    if(count%2==0){
                        System.out.println(Thread.currentThread().getName()+":"+count);
                    }
                }
            }
        }.start();
    }
}

2.3.3 Thread类的相关方法  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.company;
 
/*
 * 测试Thread的常用方法
 * 1、start():启动当前进程,执行当前进程的run()
 * 2、run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
 * 3、currentThread():静态方法,返回当前代码执行的线程
 * 4、getName():获取当前进程的进程名
 * 5、setName():设置当前进程的进程名
 * 6、yield():释放当前CPU的执行权
 * 7、join():在线程a中调用线程b的join(),此时线程a就进入了阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态
 * 8、stop():已过时。当执行此方法时,强制结束当前进程
 * 9、sleep(long millitime):让当前进程“睡眠”指定时间的millitime毫秒。在指定的millitime毫秒时间内,当前进程是阻塞状态的
 * 10、isAlive():返回boolean,判断线程是否还活着
 */
class HelloThread extends Thread{
    @Override
    public void run() {
        for(int count=0;count<10;count++){
 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            if(count%2==0){
                System.out.println(Thread.currentThread().getName() + ":"+count);
            }
        }
    }
 
    public HelloThread(String name) {
        super(name);
    }
}
public class Main {
 
    public static void main(String[] args) {
        HelloThread helloThread1=new HelloThread("Thread:1");
        helloThread1.start();
 
        //给主线程命名
        Thread.currentThread().setName("主线程");
 
        for(int count=0;count<100;count++){
            if(count%2==0){
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
 
            if(count==20){
                try{
                    helloThread1.join();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(helloThread1.isAlive());
    }
}

2.3.4、线程的调度 

  • 调度策略
    • 时间片

    • 抢占式:高优先级的线程抢占CPU
  • Java的调度方法
    • 同优先级线程组成先进先出队列(先到先服务),使用时间片策略
    • 对于高优先级,使用优先调度的抢占式策略

2.3.5、线程的优先级

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.company;
 
class HelloThread extends Thread{
    @Override
    public void run() {
        for(int count=0;count<10;count++){
 
            if(count%2==0){
                System.out.println(Thread.currentThread().getName() +getPriority()+ ":"+count);
            }
        }
    }
 
    public HelloThread(String name) {
        super(name);
    }
}
public class Main {
 
    public static void main(String[] args) {
        HelloThread helloThread1=new HelloThread("Thread:1");
        helloThread1.start();
 
        helloThread1.setPriority(Thread.MAX_PRIORITY);
        //给主线程命名
        Thread.currentThread().setName("主线程");
 
        for(int count=0;count<100;count++){
            if(count%2==0){
                System.out.println(Thread.currentThread().getName()+":"+count);
            }
        }
        System.out.println(helloThread1.isAlive());
    }
}

 设置helloThread1的优先级为最大优先级,执行结果如下:

2.3.6 创建多线程的方式二:实现Runnable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.company;
 
/*
 *创建多线程的方式二:实现Runnable接口
 * 1、创建一个实现了Runnable接口的类
 * 2、实现类去实现Runnable中的抽象方法:run()
 * 3、创建实现类的对象
 * 4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的方法
 * 5、通过Thread类的对象调用start()
 */
class HelloThread implements Runnable{
    @Override
    public void run() {
        for(int count=0;count<10;count++){
 
            if(count%2==0){
                System.out.println(Thread.currentThread().getName() + ":"+count);
            }
        }
    }
}
public class Main {
    public static void main(String[] args) {
        //3、 创建实现类的对象
        HelloThread helloThread1= new HelloThread();
        //4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
        Thread t1=new Thread(helloThread1);
        //5、通过Thread类的对象调用start():1、启动线程2、调用当前线程的run() -->调用Runnable类型的target的run()
        t1.start();
 
        // 再启动一个线程,遍历100以内的偶数
        Thread t2=new Thread(helloThread1);
        t2.setName("线程2");
        t2.start();
 
    }
}

2.3.7 继承方式和实现接口方式的联系与区别

比较创建进程的两种方式:

开发中:优先选择:实现Runnable接口的方式

原因1:实现的方式没有类的单继承性的局限性

原因2:实现的方式更适合来处理多个线程有共享数据的情况

联系:public class Thread implements Runnable

相同点:两种方式都需要重写run()方法,将线程要执行的逻辑声明在run()中 

2.3.8  线程的分类

JAVA中的线程分为两类:一种是守护进程,一种是用户进程

  • 它们在几乎每个方面都是相同的,唯一的区别在于判断JVM何时离开
  • 守护进程是用来服务用户进程的,通过在start()方法前调用**thread.setDaemon(true)**可以把一个用户线程变成一个用户进程
  • Java垃圾回收就是一个典型的守护线程
  • 若JVM中都是守护线程,当前JVM将退出

03、线程的生命周期

JDK中用Thread.State类定义了线程的几种状态

  • 新建:当一个Thread类或其子类的对象被声明并创建时,新生的线程对象处于新建状态
  • 就绪:处于新建状态的线程被Start()后,将进入线程队列等待CPU时间片,此时它已具备了运行的条件,只是没分配到CPU资源
  • 运行:当就绪的线程被调度并获取CPU资源时,便进入运行状态,run()方法定义了线程的操作和功能
  • 阻塞:在某种特殊情况下,被人为挂起或执行输入输出操作时,让出CPU并临时中止自己的执行,进入阻塞状态
  • 死亡:线程完成了它的全部工作或线程被提前强制性中止或出现异常导致结束

04、线程的同步

1、多个线程的问题

多个线程执行的不确定性会引起执行结果的不稳定

多个线程对账本的共享会造成操作的不完整性,会破坏数据

 

 

 

模拟火车站售票程序,三个窗口卖票

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.company;
 
class Windows1 implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
        while(true){
            if(ticket>0){
                System.out.println(Thread.currentThread().getName() + ":卖票,票号为:"+ticket);
                ticket --;
            }else{
                break;
            }
        }
    }
}
public class windowsTest1 {
    public static void main(String[]args){
        Windows1 windows1=new Windows1();
 
        Thread t1=new Thread(windows1);
        Thread t2=new Thread(windows1);
        Thread t3=new Thread(windows1);
 
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
 
        t1.start();
        t2.start();
        t3.start();
    }
} 

 理想状态

 

极端状态

 

 

 4.1、同步代码块处理实现Runnable的线程安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.company;
 
class Windows1 implements Runnable{
    private int ticket=100;
    @Override
    public void run() {
        while(true){
            synchronized (this) { //此时的this:唯一的windows1对象
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
public class windowsTest1 {
    public static void main(String[]args){
        Windows1 windows1=new Windows1();
 
        Thread t1=new Thread(windows1);
        Thread t2=new Thread(windows1);
        Thread t3=new Thread(windows1);
 
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
 
        t1.start();
        t2.start();
        t3.start();
    }
}

 

 

4.2、同步代码块处理继承Thread类的线程安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.company;
 
class Windows2 extends Thread{
    private static int ticket=100;
    private static Object obj=new Object();
 
    @Override
    public void run(){
        while(true){
            synchronized (Windows2.class) {
                if(ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
 
                    System.out.println(getName()+":卖票,票号为:"+ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
public class WindowsTest2 {
    public static void main(String[]args){
        Windows2 t1=new Windows2();
        Windows2 t2=new Windows2();
        Windows2 t3=new Windows2();
 
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
 
        t1.start();;
        t2.start();
        t3.start();
    }
}

4.3、同步方法处理实现Runnable的线程安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.company;
/**<br> * 使用同步方法解决实现Runnable接口的线程安全问题<br> *<br> * 关于同步方法的总结:<br> * 1、同步方法仍然涉及到同步监视器,只是不需要我们显示的声明。<br> * 2、非静态的同步方法,同步监视器是:this<br> *   静态的同步方法,同步监视器是:当前类本身<br> */<br>
class Windows3 implements Runnable{
    private int ticket=100;
 
    @Override
    public void run() {
        while(true){
            show();
        }
    }
 
    private synchronized void show() { //同步监视器
        if(ticket>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":卖票,票号为:"+ticket);
            ticket--;
        }
    }
 
}
public class windowsTest3{
    public static void main(String[]args){
        Windows3 windows3=new Windows3();
 
        Thread t1=new Thread(windows3);
        Thread t2=new Thread(windows3);
        Thread t3=new Thread(windows3);
 
        t1.start();
        t2.start();
        t3.start();
    }
}

4.4、 同步方法处理继承Thread类的继承安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.company;
 
class windows4 extends Thread{
    private static int ticket=100;
 
    @Override
    public void run(){
        while(true){
            show();
        }
    }
 
    private static synchronized void show() { //同步监视器Windows4.class
        if(ticket>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":卖票,票号为:"+ticket);
            ticket--;
        }
    }
}
public class windowsTest4 {
    public static void main(String[]args){
        windows4 t1=new windows4();
        windows4 t2=new windows4();
        windows4 t3=new windows4();
 
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
 
        t1.start();
        t2.start();
        t3.start();
    }
}

4.5、 线程安全的单例模式之懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.company;
 
public class BankTest {
}
class Bank{
    private Bank() {
 
    }
 
    private static Bank instance =null;
    
 
//   
    private static Bank getInstance(){
         // 方式一:效率较差
//         synchronized(Bank.class){
//             if(instance == null){
//                 instance = new Bank();
//             }
//             return instance;
//         }
//        方式二:效率较高
        if(instance == null){
            synchronized (Bank.class) {
                if(instance == null){
                    instance=new Bank();
                }
            }
        }
        return instance;
    }
}

 4.6、死锁的问题

死锁就是不同的线程分别占用对方所需要的同步资源不放弃,都在等待对方放弃自己所需要的同步资源,就构成了线程的死锁

出现死锁后,不会出现异常,所有线程处于阻塞状态,无法继续。

 例一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.company;
 
public class ThreadTest {
    public static void main(String[] args){
        StringBuffer s1=new StringBuffer();
        StringBuffer s2=new StringBuffer();
 
        new Thread(){
            @Override
            public void run(){
                synchronized (s1) {
                    s1.append("a");
                    s1.append("1");
 
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
 
                    synchronized (s2) {
                        s1.append("b");
                        s2.append("2");
 
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();
 
        new Thread(){
            @Override
            public void run(){
                synchronized (s2) {
                    s1.append("c");
                    s1.append("3");
 
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
 
                    synchronized (s1) {
                        s1.append("d");
                        s2.append("4");
 
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();
    }
}

 例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.company;
 
class A{
    public synchronized void foo(B b){
        System.out.println("当前线程名:"+Thread.currentThread().getName()+"进入了A实例的foo方法");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("当前线程名:"+Thread.currentThread().getName()+"企图调用B实例的last方法");
        b.last();
    }
    public synchronized void last(){
        System.out.println("进入了A类方法的last方法内部");
    }
}
class B{
    public synchronized void bar(A a){
        System.out.println("当前线程名:"+Thread.currentThread().getName()+"进入了A实例的foo方法");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("当前线程名:"+Thread.currentThread().getName()+"企图调用B实例的last方法");
        a.last();
    }
    public synchronized void last(){
        System.out.println("进入了B类方法的last方法内部");
    }
}
public class DeadLock implements Runnable{
    A a=new A();
    B b=new B();
 
    public void init(){
        Thread.currentThread().setName("主线程");
        a.foo(b);
        System.out.println("进入主线程之后");
    }
    @Override
    public void run() {
        Thread.currentThread().setName("副线程");
        b.bar(a);
        System.out.println("进入副线程之后");
    }
 
    public static void main(String[]args){
        DeadLock d1=new DeadLock();
        new Thread(d1).start();
        d1.init();
    }
}

 4.7、Lock锁方式解决线程安全问题

  • java.util.concurrent.locks.Lock接口时控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前先获取Lock对象
  • ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁、释放锁。
  • 从JDK5.0开始,Java提供了更强大的线程同步机制---通过显示定义同步锁对象来实现同步。同步锁使用Lock对象充当。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.company;
 
import java.util.concurrent.locks.ReentrantLock;
 
/*
 *解决线程安全问题的方式三:Lock锁---》JDK5.0新增
 * 注意:如果同步代码有异常,要将unlock()写入finally语句块
 *
 * 1、面试题:synchronized与lock异同?
 * 相同:二者都可以解决线程安全问题
 * 不同:synchronized机制在执行完相应的同步代码之后,自动释放同步监视器
 * Lock需要手动启动同步(lock()),同时结束同步也需要手动实现(unlock())
 *
 * 2、优先使用顺序
 *  Lock同步代码块(已经进入了方法体,分配了相应资源)
 * 同步方法(在方法体之外)
 */
class Windows implements Runnable{
    private int ticket=100;
    // 1、实例化ReentrantLock
    private ReentrantLock lock=new ReentrantLock();
 
 
    @Override
    public void run() {
        while(true){
            try {
                //调用锁定方法:lock()
                lock.lock();
                if(ticket>0){
 
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":售票,票号为:"+ticket);
                    ticket--;
                }
                else{
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
public class LockTest {
    public static void main(String[]args){
         Windows windows=new Windows();
         Thread t1=new Thread(windows);
         Thread t2=new Thread(windows);
         Thread t3=new Thread(windows);
 
         t1.setName("窗口1");
         t2.setName("窗口2");
         t3.setName("窗口3");
 
         t1.start();
         t2.start();
         t3.start();
    }
}

 例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.company;
 
class Account{
    private double balance;
 
    public Account(double balance){
        this.balance = balance;
    }
 
    // 存钱
    public synchronized void deposit(double amt){
        if(amt>0){
 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            balance+=amt;
            System.out.println(Thread.currentThread().getName()+":"+"存钱成功,当前余额为:"+balance);
        }
    }
}
 
class Customer extends Thread{
    private Account account;
 
    public Customer(Account account) {
        this.account=account;
    }
 
    @Override
    public void run(){
        for(int count=0;count<3;count++){
            account.deposit(1000);
        }
    }
}
public class AccountTest {
 
    public static void main(String[]args){
        Account acct=new Account(0);
        Customer customer1=new Customer(acct);
        Customer customer2=new Customer(acct);
 
        customer1.setName("甲");
        customer2.setName("乙");
 
        customer1.start();
        customer2.start();
 
    }
}

5、线程的通信

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.company;
 
/*
 *线程通信的例子:使用两个线程打印1-100。线程1、线程2、交替打印
 * 涉及到三个方法:
 * wait():一旦执行此方法,当前线程就进入了阻塞状态,并释放同步监视器
 * notify():一旦执行此方法,就会唤醒被wait的一个线程,如果有多个线程被wait,那就先唤醒优先级高的那个
 * notifyAll():一旦执行此方法,就会唤醒所有被wait的线程
 *
 * 说明:
 * 1、wait()、notify()、notifyAll()三个方法必须使用在同步代码块或者同步方法中
 * 2、wait()、notify()、notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器,否则,会出现IllegalMonitorStateException异常
 * 3、wait()、notify()、notifyAll()三个方法是定义在java.lang.Object中。
 */
class Number implements Runnable {
    private int number = 1;
    public Object obj=new Object();
 
    @Override
    public void run() {
        while(true){
            synchronized (obj) {
                obj.notify();
                if(number<=100){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":"+number);
                    number++;
 
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }
}
public class CommunicationTest {
    public static void main(String[]args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
 
        t1.setName("线程1");
        t2.setName("线程2");
 
        t1.start();
        t2.start();
    }
}

 

当注释掉obj.notify();

5.1 sleep() 和wait()的异同

sleep()和wait()的相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。

sleep()和wait()的不同点:

  • 两个方法声明的位置不同:Thread类中声明sleep(),Object类中声明wait()
  • 调用的要求不同:sleep()可以在任何需要的场景下调用,wait()必须使用在同步代码块或同步方法中
  • 关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。

6、JDK5.0新增的线程创建方式

6.1、创建多线程的方式三:实现Callable接口

 

  

 

  

 

 参考文档:https://blog.csdn.net/sunyingboaini/article/details/125365507?spm=1001.2014.3001.5502

posted @   leagueandlegends  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示