zoukankan      html  css  js  c++  java
  • Java学习笔记-多线程

    多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能

    进程与线程的概念

    • 进程:是一个正在执行中的程序
      每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元
    • 线程:就是进程中的一个独立的控制单元
      线程在控制着进程的执行
    • 一个进程中至少有一个线程
    • Java VM 启动的时候会有一个进程java.exe
      该进程中至少一个线程负责java程序的执行
      而且这个线程运行的代码存在于main方法中
      该线程称之为主线程
    • 扩展:
      其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程

    继承Thread类创建多线程

    创建步骤

    1. 定义类继承Thread
    2. 复写Thread类中的run方法
      目的:将自定义代码存储在run方法。让线程运行
    3. 调用线程的start方法
      该方法两个作用:启动线程,调用run方法
    class Demo extends Thread {
    	public void run() {
    		for(int x = 0; x < 10; x++)
    			System.out.println("demo run----" + x);
    	}
    }
    
    class ThreadTest {
    	public static void main(String[] args) {
    		Demo d = new Demo(); //创建好一个线程
    		d.start(); //开启线程并执行该线程的run方法
    		//d.run(); //仅仅是对象调用方法。而线程创建了,并没有运行
    		for(int x = 0; x < 10; x++)
    			System.out.println("Test!--"+x);
    	}
    }
    

    结果分析

    发现运行结果每一次都不同
    因为多个线程都获取cpu的执行权。cpu执行到谁,谁就运行
    明确一点,在某一个时刻,只能有一个程序在运行。(多核除外)
    cpu在做着快速的切换,以达到看上去是同时运行的效果
    我们可以形象把多线程的运行行为在互相抢夺cpu的执行权

    这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,cpu说的算

    为什么要覆盖run方法呢?
    Thread类用于描述线程
    该类就定义了一个功能,用于存储线程要运行的代码。该存储功能就是run方法

    也就是说Thread类中的run方法,用于存储线程要运行的代码

    使用注意事项

    • 原来线程都有自己默认的名称
      Thread-编号 该编号从0开始
    • static Thread currentThread():获取当前线程对象
    • getName(): 获取线程名称
    • 设置线程名称:setName或者构造函数

    线程状态

    线程状态
    sleep方法需要指定睡眠时间,单位是毫秒
    一个特殊的状态:就绪。具备了执行资格,但是还没有获取资源

    实现Runnable接口

    创建步骤

    1. 定义类实现Runnable接口
    2. 覆盖Runnable接口中的run方法
      将线程要运行的代码存放在该run方法中
    3. 通过Thread类建立线程对象
    4. 将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数
      为什么要将Runnable接口的子类对象传递给Thread的构造函数
      因为,自定义的run方法所属的对象是Runnable接口的子类对象
      所以要让线程去指定指定对象的run方法。就必须明确该run方法所属对象
    5. 调用Thread类的start方法开启线程并调用Runnable接口子类的run方法
    class Demo implements Runnable {
    	public void run() {
    		···
    	}
    }
    
    class Test {
    	public static void main(String[] args) {
    		Demo d = new Demo();
    		Thread t1 = new Thread(d);//创建了一个线程;
    		Thread t2 = new Thread(d);//创建了一个线程;
    		Thread t3 = new Thread(d);//创建了一个线程;
    		Thread t4 = new Thread(d);//创建了一个线程;
    		t1.start();
    		t2.start();
    		t3.start();
    		t4.start();
    	}
    }
    

    实现方式和继承方式的区别

    • 实现方式好处:避免了单继承的局限性
    • 在定义线程时,建立使用实现方式

    两种方式区别:

    • 继承Thread:线程代码存放Thread子类run方法中
    • 实现Runnable,线程代码存在接口的子类的run方法

    线程安全问题

    导致安全问题的出现的原因

    • 多个线程访问出现延迟
    • 线程随机性
      即:当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行。导致共享数据的错误

    注:线程安全问题在理想状态下,不容易出现,但一旦出现对软件的影响是非常大

    解决办法

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

    同步(synchronized)

    格式:
    同步代码块

    synchronized(对象) {
        需要同步的代码;
    }
    

    同步可以解决安全问题的根本原因就在那个对象上
    该对象如同锁的功能

    同步的特点

    同步的前提:

    • 同步需要两个或者两个以上的线程
    • 多个线程使用的是同一个锁

    未满足这两个条件,不能称其为同步

    好处:解决了多线程的安全问题
    弊端:当线程相当多时,因为每个线程都会去判断同步上的锁,这是很耗费资源的,无形中会降低程序的运行效率

    同步函数

    格式:
    在函数上加上synchronized修饰符即可

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

    class Ticket implements Runnable {
    	private int tick = 100;
    	boolean flag = true;
    	public void run() {
    		if(flag) {
    			while(true) {
    				synchronized(this) {
    					if(tick>0) {
    						try{Thread.sleep(10);}catch(Exception e){}
    						System.out.println(Thread.currentThread().getName()+"...code... : "+ tick--);
    					}
    				}
    			}
    		}
    		else
    			while(true)
    				show();
    	}
    	public synchronized void show() {
    		if(tick > 0) {
    			try{Thread.sleep(10);}catch(Exception e){}
    			System.out.println(Thread.currentThread().getName()+"....show.... : " + tick--);
    		}
    	}
    }
    
    class ThisLockDemo {
    	public static void main(String[] args) {
    
    		Ticket t = new Ticket();
    		Thread t1 = new Thread(t);
    		Thread t2 = new Thread(t);
    		t1.start();
    		try{Thread.sleep(10);}catch(Exception e){}
    		t.flag = false;
    		t2.start();
    	}
    }
    

    如果同步函数被静态修饰后,使用的锁是什么呢?
    通过验证,发现不在是this。因为静态方法中也不可以定义this
    静态进内存是,内存中没有本类对象,但是一定有该类对应的字节码文件对象
    类名.class 该对象的类型是Class
    静态的同步方法:使用的锁是该方法所在类的字节码文件对象。 类名.class

    class Ticket implements Runnable {
    	private static int tick = 100;
    	boolean flag = true;
    	public void run() {
    		if(flag) {
    			while(true) {
    				synchronized(Ticket.class) {
    					if(tick > 0) {
    						try{Thread.sleep(10);}catch(Exception e){}
    						System.out.println(Thread.currentThread().getName()+"...code... : " + tick--);
    					}
    				}
    			}
    		}
    		else
    			while(true)
    				show();
    	}
    	public static synchronized void show() {
    		if(tick > 0) {
    			try{Thread.sleep(10);}catch(Exception e){}
    			System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);
    		}
    	}
    }
    
    class StaticMethodDemo {
    	public static void main(String[] args) {
    		Ticket t = new Ticket();
    		Thread t1 = new Thread(t);
    		Thread t2 = new Thread(t);
    		t1.start();
    		try{Thread.sleep(10);}catch(Exception e){}
    		t.flag = false;
    		t2.start();
    	}
    }
    

    同步锁的运用

    1. 明确哪些代码是多线程运行代码。
    2. 明确共享数据。
    3. 明确多线程运行代码中哪些语句是操作共享数据的

    死锁

    同步中嵌套同步

    class Test implements Runnable {
    	private boolean flag;
    	Test(boolean flag) {
    		this.flag = flag;
    	}
    	public void run() {
    		if(flag) {
    			synchronized(MyLock.locka) {
    				System.out.println(Thread.currentThread().getName()+"...if locka ");
                    synchronized(MyLock.lockb) {
                        System.out.println(Thread.currentThread().getName()+"...if lockb");		
                    }
                }
            } else {
    			synchronized(MyLock.lockb) {
    				System.out.println(Thread.currentThread().getName()+"..else lockb");
    				synchronized(MyLock.locka) {
    					System.out.println(Thread.currentThread().getName()+".....else locka");
    				}
    			}
            }
    	}
    }
    
    class MyLock {
    	static Object locka = new Object();
    	static Object lockb = new Object();
    }
    
    class DeadLockTest {
    	public static void main(String[] args) {
    		Thread t1 = new Thread(new Test(true));
    		Thread t2 = new Thread(new Test(false));
    		t1.start();
    		t2.start();
    	}
    }
    

    线程间通讯

    其实就是多个线程在操作同一个资源,但是操作的动作不同
    线程间通讯

    存在问题

    线程间的通讯,涉及到有读写的时候,那么此时可能会差生问题
    在写入操作未完成便执行写操作会造成读取到的数据不匹配
    这时候需要对写入和读取加入同步锁,使得写入完毕才能读取,读取完毕才能写

    waitnotify()notifyAll()

    • wait():等待
    • notify():唤醒
    • notifyAll():唤醒全部
    • 都使用在同步中,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,因为只有同步才具有锁
    • 为什么这些操作线程的方法要定义Object类中呢?
      因为这些方法在操作同步中线程时,都必须要标识它们所操作线程持有的锁
      只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒
      不可以对不同锁中的线程进行唤醒
    • 也就是说,等待和唤醒必须是同一个锁
    • 而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中

    示例代码

    class Res {
    	String name;
    	String sex;
    	boolean flag = false;
    }
    
    class Input implements Runnable {
    	private Res r;
    	Input(Res r) {
    		this.r = r;
    	}
    	public void run() {
    		int x = 0;
    		while(true) {
    			synchronized(r) {
    				if(r.flag)
    					try{r.wait();}catch(Exception e){}
    				if(x == 0) {
    					r.name="jack";
    					r.sex="man";
    				}
    				else {
    					r.name="alen";
    					r.sex = "woman";
    				}
    				x = (x + 1) % 2;
    				r.flag = true;
    				r.notify();
    			}
    		}
    	}
    }
    
    class Output implements Runnable {
    	private Res r ;
    	Output(Res r) {
    		this.r = r;
    	}
    	public void run() {
    		while(true) {
    			synchronized(r) {
    				if(!r.flag)
    					try{r.wait();}catch(Exception e){}
    				System.out.println(r.name+"...."+r.sex);
    				r.flag = false;
    				r.notify();
    			}
    		}
    	}
    }
    
    class InputOutputDemo {
    	public static void main(String[] args) {
    		Res r = new Res();
    		Input in = new Input(r);
    		Output out = new Output(r);
    		Thread t1 = new Thread(in);
    		Thread t2 = new Thread(out);
    		t1.start();
    		t2.start();
    	}
    }
    

    优化以上代码(封装Res类)

    class Res {
    	private String name;
    	private String sex;
    	private boolean flag = false;
    	public synchronized void set(String name, String sex) {
    		if(flag)
    			try{this.wait();}catch(Exception e){}
    		this.name = name;
    		this.sex = sex;
    		flag = true;
    		this.notify();
    	}
    	public synchronized void out() {
    		if(!flag)
    			try{this.wait();}catch(Exception e){}
    		System.out.println(name+"........"+sex);
    		flag = false;
    		this.notify();
    	}
    }
    
    class Input implements Runnable {
    	private Res r ;
    	Input(Res r) {
    		this.r = r;
    	}
    	public void run() {
    		int x = 0;
    		while(true) {
    			if(x == 0)
    				r.set("jack","man");
    			else
    				r.set("alen","women");
    			x = (x + 1) % 2;
    		}
    	}
    }
    
    class Output implements Runnable {
    	private Res r ;
    	Output(Res r) {
    		this.r = r;
    	}
    	public void run() {
    		while(true) {
    			r.out();
    		}
    	}
    }
    
    class InputOutputDemo {
    	public static void main(String[] args) {
    		Res r = new Res();
    		new Thread(new Input(r)).start();
    		new Thread(new Output(r)).start();
    	}
    }
    

    生产者消费者模型

    当存在多个输入以及多个输出时候,可能导致一个输入被多次输出,多次输入值输出一个
    此时需要对代码进行改进

    主要思路是:

    • 不知线程会在何时被唤醒,因此需要在唤醒的时候做条件判断
    • 如果只唤醒本方线程,那么可能存在所有线程处于等待状态

    解决办法:

    • 定义while判断标记
      原因:让被唤醒的线程再一次判断标记
    • 使用notifyAll
      唤醒对方线程,因为只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待
    class ProducerConsumerDemo {
    	public static void main(String[] args) {
    		Resource r = new Resource();
    		Producer pro = new Producer(r);
    		Consumer con = new Consumer(r);
    		Thread t1 = new Thread(pro);
    		Thread t2 = new Thread(pro);
    		Thread t3 = new Thread(con);
    		Thread t4 = new Thread(con);
    		t1.start();
    		t2.start();
    		t3.start();
    		t4.start();
    	}
    }
    
    class Resource {
    	private String name;
    	private int count = 1;
    	private boolean flag = false;
    	public synchronized void set(String name) {
    		while(flag)
    			try{this.wait();}catch(Exception e){}
    		this.name = name+"--"+count++;
    		System.out.println(Thread.currentThread().getName() + "生产者:" + this.name);
    		flag = true;
    		this.notifyAll();
    	}
    	public synchronized void out() {
    		while(!flag)
    			try{wait();}catch(Exception e){}
    		System.out.println(Thread.currentThread().getName() + "消费者:" + this.name);
    		flag = false;
    		this.notifyAll();
    	}
    }
    
    class Producer implements Runnable {
    	private Resource res;
    	Producer(Resource res) {
    		this.res = res;
    	}
    	public void run() {
    		while(true) {
    			res.set("+商品+");
    		}
    	}
    }
    
    class Consumer implements Runnable {
    	private Resource res;
    	Consumer(Resource res) {
    		this.res = res;
    	}
    	public void run() {
    		while(true) {
    			res.out();
    		}
    	}
    }
    

    生产者与消费者模型的改进

    从JDK1.5开始提供了多线程升级解决方案
    将同步Synchronized替换成现实Lock操作
    将Object中的waitnotifynotifyAll,替换了Condition对象
    该对象可以Lock锁进行获取
    该示例中,实现了本方只唤醒对方操作

    • Lock:替代了Synchronized
      lock
      unlock
      newCondition()

    Condition:替代了Object:``wait notify notifyAll
    await();
    signal();
    signalAll();

    import java.util.concurrent.locks.*;
    
    class ProducerConsumerDemo {
    	public static void main(String[] args) {
    		Resource r = new Resource();
    		Producer pro = new Producer(r);
    		Consumer con = new Consumer(r);
    		Thread t1 = new Thread(pro);
    		Thread t2 = new Thread(pro);
    		Thread t3 = new Thread(con);
    		Thread t4 = new Thread(con);
    		t1.start();
    		t2.start();
    		t3.start();
    		t4.start();
    	}
    }
    
    class Resource {
    	private String name;
    	private int count = 1;
    	private boolean flag = false;
    	private Lock lock = new ReentrantLock();
    	private Condition condition_pro = lock.newCondition();
    	private Condition condition_con = lock.newCondition();
    
    	public void set(String name) throws InterruptedException {
    		lock.lock();
    		try{
    			while(flag)
    				condition_pro.await();
    			this.name = name+"--"+count++;
    			System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
    			flag = true;
    			condition_con.signal();
    		} finally {
    			lock.unlock();//释放锁的动作一定要执行
    		}
    	}
    	public void out() throws InterruptedException {
    		lock.lock();
    		try{
    			while(!flag)
    				condition_con.await();
    			System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);
    			flag = false;
    			condition_pro.signal();
    		} finally {
    			lock.unlock();
    		}
    	}
    }
    
    class Producer implements Runnable {
    	private Resource res;
    
    	Producer(Resource res) {
    		this.res = res;
    	}
    	public void run() {
    		while(true) {
    			try {
    				res.set("+商品+");
    			} catch (InterruptedException e) {
    			}
    		}
    	}
    }
    
    class Consumer implements Runnable {
    	private Resource res;
    
    	Consumer(Resource res) {
    		this.res = res;
    	}
    	public void run() {
    		while(true) {
    			try {
    				res.out();
    			}
    			catch (InterruptedException e) {
    			}
    		}
    	}
    }
    

    停止线程

    1. 定义循环结束标记
      因为线程运行代码一般都是循环,只要控制了循环即可
    2. 使用interrupt(中断)方法
      该方法是结束线程的冻结状态,使线程回到 运行状态中来

    注:stop方法已经过时不再使用

    如何停止线程?
    只有一种,run方法结束
    开启多线程运行,运行代码通常是循环结构
    只要控制住循环,就可以让run方法结束,也就是线程结束

    特殊情况:
    当线程处于了冻结状态
    就不会读取到标记。那么线程就不会结束

    当没有指定的方式让冻结的线程恢复到运行状态是,这时需要对冻结进行清除
    强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束

    Thread类提供该方法 interrupt();可以将冻结状态的线程唤醒

    e.g.

    class StopThread implements Runnable {
    	private boolean flag = true;
    	public synchronized void run() {
    		while(flag) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName()+"....Exception");
                    flag = false;
                }
                System.out.println(Thread.currentThread().getName()+"....run");
    		}
    	}
    }
    
    class StopThreadDemo {
    	public static void main(String[] args) {
    		StopThread st = new StopThread();
    		Thread t1 = new Thread(st);
    		Thread t2 = new Thread(st);
    		t1.start();
    		t2.start();
    		int num = 0;
    		while(true) {
    			if(num++ == 60) {
    				t1.interrupt();
    				t2.interrupt();
    				break;
    			}
    			System.out.println(Thread.currentThread().getName() + "..." + num);
    		}
    		System.out.println("over");
    	}
    }
    

    守护线程

    运行在后台的一种线程,其生命周期随着主线程的结束而结束
    之前的代码可以通过利用守护线程轻松解决
    当正在运行的线程都是守护线程时,java虚拟机退出
    该方法必须在启动线程前调用

    class StopThread implements Runnable {
    	private boolean flag = true;
    	public  void run() {
    		while(flag)
    		{
    			System.out.println(Thread.currentThread().getName()+"...run");
    		}
    	}
    }
    
    class ThreadDemo {
    	public static void main(String[] args) {
    		StopThread st = new StopThread();
    		Thread t1 = new Thread(st);
    		Thread t2 = new Thread(st);
    		t1.setDaemon(true); //定义为守护线程
    		t2.setDaemon(true);
    		t1.start();
    		t2.start();
    		int num = 0;
    		while(true) {
    			if(num++ == 60) {
    				break;
    			}
    			System.out.println(Thread.currentThread().getName()+"..."+num);
    		}
    		System.out.println("over");
    	}
    }
    

    join方法

    当A线程执行到了B线程的join()方法时,A就会等待。等B线程都执行完,A才会执行
    join可以用来临时加入线程执行

    Demo d = new Demo();
    Thread t1 = new Thread(d);
    Thread t2 = new Thread(d);
    t1.start();
    t1.join();	
    t2.start();
    

    线程优先级

    县城默认的优先级为5
    使用setPriority()方法设置线程优先级

    t1.setPriority(Thread.MAX_PRIORITY);
    

    yield方法

    暂停当前正在执行的线程对象,并执行其他线程

    Thread.yield();
    
  • 相关阅读:
    Mac OS Git 安装
    Android Studio Emulator 提示 “/dev/kvm is not found” 解决办法
    Intel haxm安装失败问题解决
    清空git缓存
    Android Studio使用过程中Java类突然报红,但项目可运行解决方案
    Nice Messager隐私权政策
    Android应用内 代码截屏(获取View快照)和 禁止截屏
    Android Studio生成APK自动追加版本号、自定义apk名称、指定签名证书文件
    Task-based Asynchronous Operation in WCF z
    task可声明参数 z
  • 原文地址:https://www.cnblogs.com/cj5785/p/10664855.html
Copyright © 2011-2022 走看看