java多线程基本使用

一.概念

1.进程

1.1进程:是一个正在进行中的程序,每一个进程执行都有一个执行顺序,该顺序是一个执行路径,或者叫一个控制单元。

1.2线程:就是进程中一个独立的控制单元,线程在控制着进程的执行,一个进程中至少有一个线程。

1.3举例java VM:

Java VM启动的时候会有一个进程java.exe,该进程中至少有一个线程在负责java程序的运行,而且这个线程运行的代码存在于main方法中,该线程称之为主线程。扩展:其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程

2.多线程存在的意义:提高执行效率

二.多线程的创建

1.多线程创建的第一种方式,继承Thread类

1.1定义类继承Thread,复写Thread类中的run方法是为了将自定义的代码存储到run方法中,让线程运行

1.2调用线程的start方法,该方法有两个作用:启动线程,调用run方法

1.3多线程运行的时候,运行结果每一次都不同,因为多个线程都获取cpu的执行权,cpu执行到谁,谁就运行,明确一点,在某一个时刻,只能有一个程序在运行。(多核除外),cpu在做着快速的切换,以到达看上去是同时运行的效果。我们可以形象把多线程的运行行为在互抢cpu的执行权。这就是多线程的一个特性,随机性。谁抢到,谁执行,至于执行多久,cpu说了算。

 1 public class Demo extends Thread{
 2     public void run(){
 3         for (int x = 0; x < 60; x++) {
 4             System.out.println(this.getName()+"demo run---"+x);
 5         }
 6     }
 7     
 8     public static void main(String[] args) {
 9         Demo d=new Demo();//创建一个线程
10         d.start();//开启线程,并执行该线程的run方法
11         d.run(); //仅仅是对象调用方法,而线程创建了但并没有运行
12         for (int x = 0; x < 60; x++) {
13             System.out.println("Hello World---"+x);
14         }
15     }
16 
17 }
View Code

2 创建多线程的第二种方式,步骤:

2.1定义类实现Runnable接口

2.2覆盖Runnable接口中的run方法:将线程要运行的代码存放到run方法中

2.3.通过Thread类建立线程对象

2.4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数

为什么要将Runnable接口的子类对象传递给Thread的构造函数:因为自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去执行指定对象的run方法,就必须明确该run方法的所属对象

2.5.调用Thread类的start方法开启线程并调用Runnable接口子类的方法

 1 /*
 2  * 需求:简易买票程序,多个窗口同时卖票
 3  */
 4 public class Ticket implements Runnable {
 5     private static int tick = 100;
 6     Object obj = new Object();
 7     boolean flag=true;
 8 
 9     public void run() {
10         if(flag){
11             while (true) {
12                 synchronized (Ticket.class) {
13                     if (tick > 0) {
14                         System.out.println(Thread.currentThread().getName()
15                                 + "code:" + tick--);
16                     }
17                 }
18             }
19         }else{
20             while(true){
21                 show();
22             }
23         }
24         
25     }
26 
27     public static synchronized void show() {
28         if (tick > 0) {
29             System.out.println(Thread.currentThread().getName() + "show:"
30                     + tick--);
31         }
32     }
33 
34 }
35 
36 class ThisLockDemo {
37     public static void main(String[] args) {
38         Ticket t = new Ticket();
39 
40         Thread t1 = new Thread(t);
41         try {
42             Thread.sleep(10);
43         } catch (Exception e) {
44             // TODO: handle exception
45         }
46         t.flag=false;
47         Thread t2 = new Thread(t);
48         //Thread t3 = new Thread(t);
49         //Thread t4 = new Thread(t);
50 
51         t1.start();
52         t2.start();
53         //t3.start();
54         //t4.start();
55     }
56 }
View Code

3.实现方式和继承方式有什么区别

3.1.实现方式避免了单继承的局限性,在定义线程时建议使用实现方式

3.2.继承Thread类:线程代码存放在Thread子类run方法中

3.3.实现Runnable:线程代码存放在接口的子类run方法中

4.多线程-run和start的特点

4.1为什么要覆盖run方法呢:

Thread类用于描述线程,该类定义了一个功能,用于存储线程要运行的代码,该存储功能就是run方法,也就是说该Thread类中的run方法,用于存储线程要运行的代码

5.多线程运行状态

创建线程-运行---sleep()/wait()--冻结---notify()---唤醒

创建线程-运行---stop()—消亡

创建线程-运行---没抢到cpu执行权—临时冻结

6.获取线程对象及其名称

6.1.线程都有自己默认的名称,编号从0开始

6.2.static Thread currentThread():获取当前线程对象

6.3.getName():获取线程名称

6.4.设置线程名称:setName()或者使用构造函数

 1 public class Test extends Thread{
 2     
 3     Test(String name){
 4         super(name);
 5     }
 6     
 7     public void run(){
 8         for (int x = 0; x < 60; x++) {
 9             System.out.println((Thread.currentThread()==this)+"..."+this.getName()+" run..."+x);
10         }
11     }
12 }
13 
14 class ThreadTest{
15     public static void main(String[] args) {
16         Test t1=new Test("one---");
17         Test t2=new Test("two+++");
18         t1.start();
19         t2.start();
20         t1.run();
21         t2.run();
22         for (int x = 0; x < 60; x++) {
23             System.out.println("main----"+x);
24         }
25     }
26 }
View Code

三.多线程的安全问题

1.多线程出现安全问题的原因:

1.1.当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行,导致共享数据的错误

1.2.解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行

1.3.java对于多线程的安全问题提供了专业的解决方式,就是同步代码块:

Synchronized(对象){需要被同步的代码},对象如同锁,持有锁的线程可以在同步中执行,没有持有锁的线程即使获取cpu执行权,也进不去,因为没有获取锁

2.同步的前提:

2.1.必须要有2个或者2个以上线程

2.2.必须是多个线程使用同一个锁

2.3.好处是解决了多线程的安全问题

2.4.弊端是多个线程需要判断锁,较消耗资源

5.同步函数

定义同步函数,在方法钱用synchronized修饰即可

 1 /*
 2  * 需求:
 3  * 银行有一个金库,有两个储户分别存300元,每次存100元,存3次
 4  * 目的:该程序是否有安全问题,如果有,如何解决
 5  * 如何找问题:
 6  * 1.明确哪些代码是多线程代码
 7  * 2.明确共享数据
 8  * 3.明确多线程代码中哪些语句是操作共享数据的
 9  */
10 
11 public class Bank {
12 
13     private int sum;
14 
15     Object obj = new Object();
16 
17     //定义同步函数,在方法钱用synchronized修饰即可
18     public synchronized void add(int n) {
19         //synchronized (obj) {
20             sum = sum + n;
21             try {
22                 Thread.sleep(10);
23             } catch (InterruptedException e) {
24                 // TODO Auto-generated catch block
25                 e.printStackTrace();
26             }
27             System.out.println("sum=" + sum);
28         //}
29 
30     }
31 
32 }
33 
34 class Cus implements Runnable {
35     private Bank b = new Bank();
36 
37     public void run() {
38         for (int x = 0; x < 3; x++) {
39             b.add(100);
40         }
41     }
42 }
43 
44 class BankDemo {
45     public static void main(String[] args) {
46         Cus c = new Cus();
47         Thread t1 = new Thread(c);
48         Thread t2 = new Thread(c);
49 
50         t1.start();
51         t2.start();
52     }
53 }
View Code

6.同步的锁

6.1函数需要被对象调用,那么函数都有一个所属对象引用,就是this.,所以同步函数使用的锁是this

6.2.静态函数的锁是class对象

静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象,类名.class,该对象的类型是Class

6.3.静态的同步方法,使用的锁是该方法所在类的字节码文件对象,类名.class

 1 /*
 2  * 需求:简易买票程序,多个窗口同时卖票
 3  */
 4 public class Ticket implements Runnable {
 5     private static int tick = 100;
 6     Object obj = new Object();
 7     boolean flag=true;
 8 
 9     public void run() {
10         if(flag){
11             while (true) {
12                 synchronized (Ticket.class) {
13                     if (tick > 0) {
14                         System.out.println(Thread.currentThread().getName()
15                                 + "code:" + tick--);
16                     }
17                 }
18             }
19         }else{
20             while(true){
21                 show();
22             }
23         }
24         
25     }
26 
27     public static synchronized void show() {
28         if (tick > 0) {
29             System.out.println(Thread.currentThread().getName() + "show:"
30                     + tick--);
31         }
32     }
33 
34 }
35 
36 class ThisLockDemo {
37     public static void main(String[] args) {
38         Ticket t = new Ticket();
39 
40         Thread t1 = new Thread(t);
41         try {
42             Thread.sleep(10);
43         } catch (Exception e) {
44             // TODO: handle exception
45         }
46         t.flag=false;
47         Thread t2 = new Thread(t);
48         //Thread t3 = new Thread(t);
49         //Thread t4 = new Thread(t);
50 
51         t1.start();
52         t2.start();
53         //t3.start();
54         //t4.start();
55     }
56 }
View Code

7.多线程,单例模式-懒汉式

懒汉式与饿汉式的区别:懒汉式能延迟实例的加载,如果多线程访问时,懒汉式会出现安全问题,可以使用同步来解决,用同步函数和同步代码都可以,但是比较低效,用双重判断的形式能解决低效的问题,加同步的时候使用的锁是该类锁属的字节码文件对象

 1 /*
 2  * 单例模式
 3  */
 4 //饿汉式
 5 public class Single {
 6     private static final Single s=new Single();
 7     private Single(){}
 8     public static Single getInstance(){
 9         return s;
10     }
11 
12 }
13 
14 //懒汉式
15 class Single2{
16     private static Single2 s2=null;
17     private Single2(){}
18     public static Single2 getInstance(){
19         if(s2==null){
20             synchronized(Single2.class){
21                 if(s2==null){
22                     s2=new Single2();    
23                 }
24             }
25         }
26         return s2;
27     }
28 }
29 
30 class SingleDemo{
31     public static void main(String[] args) {
32         System.out.println("Hello World");
33     }
34 }
View Code

8.多线程-死锁

同步中嵌套同步会出现死锁

 1 /*
 2  * 需求:简易买票程序,多个窗口同时卖票
 3  */
 4 public class DeadTest implements Runnable {
 5     private boolean flag;
 6 
 7     DeadTest(boolean flag) {
 8         this.flag = flag;
 9     }
10 
11     public void run() {
12         if (flag) {
13             synchronized(MyLock.locka){
14                 System.out.println("if locka");
15                 synchronized(MyLock.lockb){
16                     System.out.println("if lockb");
17                 }
18             }
19         } else {
20             synchronized(MyLock.lockb){
21                 System.out.println("else lockb");
22                 synchronized(MyLock.locka){
23                     System.out.println("else locka");
24                 }
25             }
26         }
27     }
28 }
29 
30 class MyLock{
31     static Object locka=new Object();
32     static Object lockb=new Object();
33 }
34 
35 class DeadLockDemo {
36     public static void main(String[] args) {
37         Thread t1 = new Thread(new DeadTest(true));
38         Thread t2 = new Thread(new DeadTest(false));
39 
40         t1.start();
41         t2.start();
42     }
43 }
View Code

四、JDK1.5新增多线程创建方式

 1、实现Callable接口

package com.lxj.juc;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
 
public class TestCallable1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        CallableDemo callableDemo = new CallableDemo();
        FutureTask futureTask = new FutureTask<>(callableDemo); 
        new Thread(futureTask).start();
        List<Integer> lists = (List<Integer>)futureTask.get(); //获取返回值
        for (Integer integer : lists) {
            System.out.print(integer + "  ");
        }
    }
}
 
class CallableDemo implements Callable<List<Integer>>{
 
    @Override
    public List<Integer> call() throws Exception {
        boolean flag = false;
        List<Integer> lists = new ArrayList<>();
        for(int i  = 3 ; i < 100 ; i ++) {
            flag = false;
            for(int j = 2; j <= Math.sqrt(i) ; j++) {
                if(i % j == 0) {
                    flag = true;
                    break;
                }
            }
            if(flag == false) {
                lists.add(i);
            }
        }
        return lists;
    }
    
}
View Code

2、线程池创建多线程

package com.lxj.juc;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class TestThreadPool {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future<List<Integer>>> ints = new ArrayList<>();
        for(int i = 0 ; i < 5; i ++) {
            Future<List<Integer>> future = executorService.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    boolean flag = false;
                    System.out.println(Thread.currentThread().getName()+"  ");
                    List<Integer> lists = new ArrayList<>();
                    for(int i  = 3 ; i < 100 ; i ++) {
                        flag = false;
                        for(int j = 2; j <= Math.sqrt(i) ; j++) {
                            if(i % j == 0) {
                                flag = true;
                                break;
                            }
                        }
                        if(flag == false) {
                            lists.add(i);
                        }
                    }
                    return lists;
                }
            });
            ints.add(future);
        }
        
        for (Future<List<Integer>> future : ints) {
            System.out.println(future.get());
        }
    }
}
 
class ThreadPoolDemo {
 
}
View Code

                                                          ----------技术改变生活,知识改变命运!

.

原文地址:https://www.cnblogs.com/liwu/p/6036812.html