11-1、多线程

1、线程的概念模型

  • 1、程序、进程、线程的概念。
  • 程序:是为完成特定任务、用某种语言编写的一组指令的集合。即指一段静态的代码,静态对象。
  • 进程:是程序的一次执行过程,或是正在运行的一个程序。动态过程,有它自身的产生、存在、消亡的过程。程序是静态的,进程是动态的。
  • 线程:线程可进一步细化为线程,是一个程序内部的一条执行路径。
    例如:360 安全卫士,运行时为进程,电脑杀毒、漏洞修复等每个功能同时执行时即为多线程的同时执行。
    每个 java 程序都隐含着一个主线程:main 方法。
  • 2、何时需要多线程?

程序需要同时执行两个或多个任务时。
程序需要实现一些等待任务时:用户输入、文件读写操作、网络操作、搜索等。
需要一些后台运行程序时。

注意:被重写的方法不能抛出比父类更大的异常。


2、线程的生命周期

线程的生命周期
线程的生命周期

  • 线程的五种状态(即生命周期)。
  • 新建状态(New)
    当创建了一个Thread对象时,该对象就处于“新建状态”,没有启动,因此无法运行
    可执行状态(Runnable),其他线程调用了处于新建状态线程的 start 方法,该线程对象将转换到“可执行状态”,线程拥有获得 CPU 控制权的机会,处在等待调度阶段。
  • 运行状态(Running)
    处在“可执行状态”的线程对象一旦获得了 CPU 控制权,就会转换到“执行状态”,在“执行状态”下,线程状态占用 CPU 时间片段,执行 run 方法中的代码,处在“执行状态”下的线程可以调用 yield 方法,该方法用于主动出让 CPU 控制权。线程对象出让控制权后回到“可执行状态”,重新等待调度。
  • 阻塞状态(Blocking)
    线程在“执行状态”下由于受某种条件的影响会被迫出让 CPU 控制权,进入“阻塞状态”。
    进入阻塞状态的三种情况:调用 sleep 方法、调用 join 方法、执行 I/O 操作。
  • 死亡状态(Dead):
    处于“执行状态”的线程一旦从 run 方法返回(无论是正常退出还是抛出异常),就会进入“死亡状态”。已经“死亡”的线程不能重新运行,否则会抛出 IllegalThreadStateException ,可以使用 Thread 类的 isAlive 方法判断线程是否活着。

3、线程的创建和启动

  • 1、单线程代码示例
//单线程:主线程,单线程的执行可以串成一条线来看
public class TestMain {
public static void main(String[] args) {
method2("atguigu.com");
}
public static void method1(String str){
System.out.println("method1....");
System.out.println(str);
}
public static void method2(String str){
System.out.println("method2...");
method1(str);
}
}
  • 2、多线程代码实例

2-1、通过继承 Thread 的方式

/*
 * 创建一个子线程,完成1-100之间自然数的输出。同样地,主线程执行同样的操作
 * 创建多线程的第一种方式:继承java.lang.Thread类
 */
//1.创建一个继承于Thread的子类
class SubThread extends Thread{
//2.重写Thread类的run()方法.方法内实现此子线程要完成的功能
public void run(){
for(int i = 1;i <= 100;i++){
System.out.println(Thread.currentThread().getName() +":" + i);
}
}
}
 
 //测试 类
public class TestThread {
public static void main(String[] args) {
//3.创建子类的对象
SubThread st1 = new SubThread();
SubThread st2 = new SubThread();
 
//4.调用线程的start():启动此线程;调用相应的run()方法
//一个线程只能够执行一次start()
//不能通过Thread实现类对象的run()去启动一个线程
st1.start();
 
//st.start();
//st.run();
st2.start();
 
for(int i = 1;i <= 100;i++){
System.out.println(Thread.currentThread().getName() +":" + i);
}
}
}

附:线程的 Thread 类的常用方法

/*
 * Thread的常用方法:
 * 1.start():启动线程并执行相应的run()方法
 * 2.run():子线程要执行的代码放入run()方法中
 * 3.currentThread():静态的,调取当前的线程
 * 4.getName():获取此线程的名字
 * 5.setName():设置此线程的名字
 * 6.yield():调用此方法的线程释放当前CPU的执行权
 * 7.join():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕,
 * A线程再接着join()之后的代码执行
 * 8.isAlive():判断当前线程是否还存活
 * 9.sleep(long l):显式的让当前线程睡眠l毫秒
 * 10.线程通信:wait()   notify()  notifyAll()
 *  * 设置线程的优先级
 * getPriority() :返回线程优先值
   setPriority(int newPriority) :改变线程的优先级
 
 */
class SubThread1 extends Thread {
public void run() {
for (int i = 1; i <= 100; i++) {
// try {
// Thread.currentThread().sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + ":"
 * Thread.currentThread().getPriority() + ":" + i);
}
}
}
 
public class TestThread1 {
public static void main(String[] args) {
 
SubThread1 st1 = new SubThread1();
st1.setName("子线程1");
st1.setPriority(Thread.MAX_PRIORITY);
st1.start();
Thread.currentThread().setName("========主线程");
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + ":"
 * Thread.currentThread().getPriority() + ":" + i);
// if(i % 10 == 0){
// Thread.currentThread().yield();
// }
// if(i == 20){
// try {
// st1.join();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
System.out.println(st1.isAlive());
}
}

2-2、通过实现 Runnable 接口的方式。

/*
 * 创建多线程的方式二:通过实现的方式
 *
 * 对比一下继承的方式 vs 实现的方式
 * 1.联系:public class Thread implements Runnable
 * 2.哪个方式好?实现的方式优于继承的方式
 *    why?  ① 避免了java单继承的局限性。
            *                  2、如果多个线程要操作同一份资源(或数据),更适合使用实现的方式
 */
//1.创建一个实现了Runnable接口的类
class PrintNum1 implements Runnable {
//2.实现接口的抽象方法
public void run() {
// 子线程执行的代码
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
 
public class TestThread1 {
public static void main(String[] args) {
//3.创建一个Runnable接口实现类的对象
PrintNum1 p = new PrintNum1();
//                p.start();
//                p.run();
//要想启动一个多线程,必须调用start()
//4.将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程
Thread t1 = new Thread(p);
//5.调用start()方法:启动线程并执行run()
t1.start();//启动线程;执行Thread对象生成时构造器形参的对象的run()方法。
 
//再创建一个线程
Thread t2 = new Thread(p);
t2.start();
}
}
  • 3、练习
练习:
1、模拟火车站售票窗口,开启三个售票窗口,票的总数为100张。(存在线程安全问题)
 
代码示例:
//模拟火车站售票窗口,开启三个窗口售票,总票数为100张
//使用继承Thread 的方式
//存在线程的安全问题
class Window extends Thread {
static int ticket = 100;
 
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "售票,票号为:"
+ ticket--);
} else {
break;
}
}
}
}
 
public class TestWindow {
public static void main(String[] args) {
Window w1 = new Window();
Window w2 = new Window();
Window w3 = new Window();
 
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
 
w1.start();
w2.start();
w3.start();
 
 
}
 
}
*******************************************
//使用实现Runnable接口的方式,售票
/*
 * 此程序存在线程的安全问题:打印车票时,会出现重票、错票
 */
 
class Window1 implements Runnable {
int ticket = 100;
 
public void run() {
while (true) {
if (ticket > 0) {
//                                try {
//                                        Thread.currentThread().sleep(10);
//                                } catch (InterruptedException e) {
//                                        // TODO Auto-generated catch block
//                                        e.printStackTrace();
//                                }
System.out.println(Thread.currentThread().getName() + "售票,票号为:"
+ ticket--);
} else {
break;
}
}
}
}
 
public class TestWindow1 {
public static void main(String[] args) {
Window1 w = new Window1();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
 
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
 
t1.start();
t2.start();
t3.start();
}
}
 
 
2、上题中会存在线程安全问题,打印车票时出现重票、错票。此问题可以通过使线程成为挂起的状态放大错误。
* 1.线程安全问题存在的原因?
 *   由于一个线程在操作共享数据过程中,未执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。
 *  
 * 2.如何来解决线程的安全问题?
 *          必须让一个线程操作共享数据完毕以后,其它线程才有机会参与共享数据的操作。
 *
 * 3.java如何实现线程的安全:线程的同步机制
 *                 
 *                 方式一:同步代码块
 *                 synchronized(同步监视器){
 *                         //需要被同步的代码块(即为操作共享数据的代码)
 *                 }
 *                 1.共享数据:多个线程共同操作的同一个数据(变量)
 *                 2.同步监视器:由一个类的对象来充当。哪个线程获取此监视器,谁就执行大括号里被同步的代码。俗称:锁
 *                 要求:所有的线程必须共用同一把锁!
 *                 注:在实现的方式中,考虑同步的话,可以使用this来充当锁。但是在继承的方式中,慎用this!
 *
 *                 方式二:同步方法
  *                      将操作共享数据的方法声明为synchronized。即此方法为同步方法,能够保证当其中一个线程执行
 *                 此方法时,其它线程在外等待直至此线程执行完此方法。
 *                 >同步方法的锁:this
 *
 * 4.线程的同步的弊端:由于同一个时间只能有一个线程访问共享数据,效率变低了。
 
代码示例:
使用同步代码块处理:
class Window2 implements Runnable {
int ticket = 100;// 共享数据
//        Object obj = new Object();
public void run() {
//                Animal a = new Animal();//局部变量
while (true) {
synchronized (this) {//this表示当前对象,本题中即为w
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "售票,票号为:" + ticket--);
}
}
}
}
}
 
public class TestWindow2 {
public static void main(String[] args) {
Window2 w = new Window2();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
 
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
 
t1.start();
t2.start();
t3.start();
}
}
class Animal{
 
}

4、线程的互斥和同步

  • 1、线程同步、线程互斥

线程同步的理解:如同说话“你说完,我再说”,协同步调。进程、线程同步,可理解为进程或线程 A 和 B一块配合,A 执行到一定程度时要依靠B的某个结果,于是停下来,示意 B 运行;B 依言执行,再将结果给 A;A 再继续操作。

线程互斥:指某一资源同时只允许一个访问者对其进行访问,具有唯一性和排它性。即保证线程同步。

  • 2、死锁问题
代码示例:
//死锁的问题:处理线程同步时容易出现。
//不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁
//写代码时,要避免死锁!
public class TestDeadLock {
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
 
public static void main(String[] args) {
new Thread() {
public void run() {
synchronized (sb1) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb1.append("A");
synchronized (sb2) {
sb2.append("B");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
 
new Thread() {
public void run() {
synchronized (sb2) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sb1.append("C");
synchronized (sb1) {
sb2.append("D");
System.out.println(sb1);
System.out.println(sb2);
}
}
}
}.start();
}
 
}
  • 3、生产者和消费者问题

此实例涵盖了线程的所有内容。
/*

  • 生产者/消费者问题
  • 生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,
  • 店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,
  • 如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,
  • 如果店中有产品了再通知消费者来取走产品。

分析:
1.是否涉及到多线程的问题?是!生产者、消费者
2.是否涉及到共享数据?有!考虑线程的安全
3.此共享数据是谁?即为产品的数量
4.是否涉及到线程的通信呢?存在这生产者与消费者的通信

 */
class Clerk{//店员
int product;
}
public synchronized void addProduct(){//生产产品
if(product >= 20){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
product++;
System.out.println(Thread.currentThread().getName() + ":生产了第" + product + "个产品");
notifyAll();
}
}
public synchronized void consumeProduct(){//消费产品
if(product <= 0){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println(Thread.currentThread().getName() + ":消费了第" + product + "个产品");
product--;
notifyAll();
}
}
}
 
class Producer implements Runnable{//生产者
Clerk clerk;
 
public Producer(Clerk clerk){
this.clerk = clerk;
}
public void run(){
System.out.println("生产者开始生产产品");
while(true){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.addProduct();
 
}
}
}
class Consumer implements Runnable{//消费者
Clerk clerk;
public Consumer(Clerk clerk){
this.clerk = clerk;
}
public void run(){
System.out.println("消费者消费产品");
while(true){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.consumeProduct();
}
}
}
 
 
public class TestProduceConsume {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer p1 = new Producer(clerk);
Consumer c1 = new Consumer(clerk);
Thread t1 = new Thread(p1);//一个生产者的线程
Thread t3 = new Thread(p1);
Thread t2 = new Thread(c1);//一个消费者的线程
 
t1.setName("生产者1");
t2.setName("消费者1");
t3.setName("生产者2");
 
t1.start();
t2.start();
t3.start();
}
}

5、临界资源、对象锁、线程通信

练习:

  • 1、临界资源与对象锁
    • 临界资源:多道程序系统中存在许多进程,它们共享各种资源,然而有很多资源一次只能供一个进程使用。一次仅允许一个进程使用的资源称为临界资源。

    • 对象锁:是指Java为临界区synchronized(Object)语句指定的对象进行加锁,对象锁是独占排他锁

1、使用同步代码块解决售票时出现的错票、重票、漏票。
 
代码示例:
实现的处理方式
class Window2 implements Runnable {
int ticket = 100;// 共享数据
//        Object obj = new Object();
public void run() {
//                Animal a = new Animal();//局部变量
while (true) {
synchronized (this) {//this表示当前对象,本题中即为w
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "售票,票号为:" + ticket--);
}
}
}
}
}
 
public class TestWindow2 {
public static void main(String[] args) {
Window2 w = new Window2();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
 
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
 
t1.start();
t2.start();
t3.start();
}
}
class Animal{
 
}
*********************************
继承的处理方式
class Window3 extends Thread {
static int ticket = 100;
static Object obj = new Object();
 
public void run() {
while (true) {
// synchronized (this) {//在本问题中,this表示:w1,w2,w3
synchronized (obj) {
// show();
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "售票,票号为:" + ticket--);
}
}
}
}
 
public synchronized void show() {// this充当的锁
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:"
+ ticket--);
}
}
}
 
public class TestWindow3 {
public static void main(String[] args) {
Window3 w1 = new Window3();
Window3 w2 = new Window3();
Window3 w3 = new Window3();
 
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
 
w1.start();
w2.start();
w3.start();
 
}
 
}
 
2、使用同步方法 解决售票时出现的错票、重票、漏票。
代码示例:
处理实现的方式
class Window4 implements Runnable {
int ticket = 100;// 共享数据
 
public void run() {
while (true) {
show();
}
}
 
public synchronized void show() {
 
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售票,票号为:"
+ ticket--);
}
 
}
}
 
public class TestWindow4 {
public static void main(String[] args) {
Window4 w = new Window4();
Thread t1 = new Thread(w);
Thread t2 = new Thread(w);
Thread t3 = new Thread(w);
 
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
 
t1.start();
t2.start();
t3.start();
}
}
 
2、银行有一个账户。有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额。
 
1.是否涉及到多线程?是!有两个储户(两种方式创建多线程)
2.是否有共享数据?有!同一个账户
3.得考虑线程的同步。(两种方法处理线程的安全)
 
//拓展:实现二者交替打印。使用线程的通信
 
代码示例:
class Account{
double balance;//余额
public Account(){
 
}
//存钱
public synchronized void deposit(double amt){
notify();
balance += amt;
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + balance);
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Customer extends Thread{
Account account;
 
public Customer(Account account){
this.account = account;
}
 
public void run(){
for(int i = 0;i < 3;i++){
account.deposit(1000);
}
}
}
 
 
 
public class TestAccount {
public static void main(String[] args) {
Account acct = new Account();
Customer c1 = new Customer(acct);
Customer c2 = new Customer(acct);
 
c1.setName("甲");
c2.setName("乙");
 
c1.start();
c2.start();
}
 
}
  • 2、线程通信
    当一个线程正在使用同步方法时,其他线程就不能使用这个同步方法,而有时涉及一些特殊情况:
    当一个人在一个售票窗口排队买电影票时,如果她给售票员的不是零钱,而售票员有没有售票员找她,那么她必须等待,并允许后面的人买票,以便售票员获取零钱找她,如果第2个人也没有零钱,那么她俩必须同时等待。
    当一个线程使用的同步方法中用到某个变量,而此变量又需要其他线程修改后才能符合本线程的需要,那么可以在同步方法中使用 wait() 方法。

wait()方法:
中断方法的执行,使本线程等待,暂时让出 cpu 的使用权,并允许其他线程使用这个同步方法。
notify()方法:
唤醒由于使用这个同步方法而处于等待线程的 某一个结束等待
notifyall()方法:
唤醒所有由于使用这个同步方法而处于等待的线程结束等待

练习:
1、使用两个线程打印 1-100. 线程1, 线程2 交替打印。
代码示例:
class PrintNum implements Runnable {
int num = 1;
Object obj = new Object();
public void run() {
while (true) {
synchronized (obj) {
obj.notify();
if (num <= 100) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":"
+ num);
num++;
} else {
break;
}
 
try {
obj.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
 
}
 
public class TestCommunication {
public static void main(String[] args) {
PrintNum p = new PrintNum();
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
 
t1.setName("甲");
t2.setName("乙");
 
t1.start();
t2.start();
}
}

2、模拟3个人,张飞、关羽和刘备,来买电影票,售票员只有一张5元的钱,电影票5元钱一张:张飞拿20元一张的人民币排在关羽和刘备的前面,关羽和刘备各拿了一张5元的人民币买票。因此张飞必须等待(还是关羽和刘备先买了票)。

class TicketsHouse implements Runnable { 
int fiveAmount 
I , tenAmount 
— twentyAmount 
public void run ( ) { 
if (Thread. current Thread() . equals( ) { 
saleTicket (2ø) ; 
else if (Thread. current-Thread() getName() . equals( 
sale Ticket ( 5) ; 
else if (Thread. current Thread() . getName() . equals( 
saleTicket ( 5) , 
private synchronized void saleTicket (int money) { 
if (money 
fiveAmount fiveAmount + I; 
System. out . print + Thread . current-Thread() . getName() 
+ Thread current Thread() . getName() + • •mJUiEif" ) ; 
else if (money 
2ø) { 
while (fiveAmount < 3) { 
try { 
System . out . println( " " 
wait ( ) ; 
/ / Thread . sleep( ; 
System . out . print Nn 
+ Thread . current ) . getName() 
+ Thread . current Thread ( ) . getName() 
catch (InterruptedException e) { 
f i veAmount 
t e nAmo unt 
five Amount 
tenAmount + I • 
System . out . print + Thread. current Thread() . getName() + 
+ Thread . current Thread() . getName() + • % 2ø. 
notifyAII ( ) ; 
// notify ( ) ;

public class BuyTicketsThread { 
public static void main(String[] args) { 
new TicketsHouse(); 
TicketsHouse officer = 
new Thread(officer); 
Thread zhangfei = 
zhangfei • setName ( " ) ; 
new Thread(officer); 
Thread likui = 
likui . setName ( " ) ; 
new Thread(officer); 
Thread Iiubei = 
Iiubei . setName ( "ilJfi " ) ; 
zhangfei . start(); 
likui . start(); 
Iiubei . start();
posted @ 2021-05-18 09:29  星命定轨  阅读(77)  评论(0编辑  收藏  举报