Java第十一章多线程

多线程:

  涉及内容:

    1.创建多线程的两种方式。

    2.线程的生命周期

    3.线程的安全问题

    4.多线程死锁

    5.多线程通信

创建多线程的第一种方式:继承java.lang.Thread

//创建多线程的第一种方式:继承java.lang.Thread类
//创建一个继承于Thread类的run()方法
class MyThread 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.创建子类的对象
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        //4.调用线程的start()方法:启动此线程;调用相应的run()方法
        //一个线程只能够执行一次start()
        //不能通过Thread实现类对象的run()去启动一个线程
        mt1.start();
        mt2.start();
        for(int i=1;i<100;i++){
            System.out.println(Thread.currentThread().getName() + ":" + i );
        }
    }
}

 Thread的常用方法:

    1.start():启动线程并执行相应的run()方法

    2.run():子线程要执行的代码放入run()方法中

    3.currentThread():静态的,获取当前的线程

    4.getName():获取线程的名字

    5.setName():设置线程的名字

    6.yield():调用此方法的线程释放当前cpu的执行权

    7.jion():在A线程中调用B线程的join()方法,表示:当执行到此方法,A线程停止执行,直至B线程执行完毕。

    8.isAlive():判断当前线程是否还存活

    9.sleep(long l):显式的让当前线程睡眠l毫秒

    10.线程通信:wait()    notify()    notifyAll()

    设置线程优先级

      getPriority():返回线程优先级

      setPriority():改变线程的优先级 

      MAX_PRIORITY(10);

      MIN_PRIORITY(1);

      NORM_PRIORITY(5);

    继承于Thread类的匿名类的对象

    new Thread(){

    

    }.start();

//火车站售票,三个窗口售票,共100张票
class ThreadWindow 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 TestThread2 {
    public static void main(String[] args) {
        ThreadWindow tw1 = new ThreadWindow();
        ThreadWindow tw2 = new ThreadWindow();
        ThreadWindow tw3 = new ThreadWindow();
        
        tw1.setName("窗口1");
        tw2.setName("窗口2");
        tw3.setName("窗口3");
        
        tw1.start();
        tw2.start();
        tw3.start();
    }    
}

 创建多线程的第二种方式:实现的方式

//1.创建一个实现Runnable接口的类
class impl implements Runnable{
    //2.实现接口的方法
    public void run() {
        //线程执行程序
    }
}


public class TestThread3 {

        public static void main(String[] args) {
            //3.创建一个Runnable接口实现类的对象
            impl i = new impl();
            //要想启动一个多线程,必须调用start()
            //4.将此对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程。
            Thread t1 = new Thread(i);
            //5.调用start()方法,启动run()方法
            t1.start();
            //启动线程:执行Thread对象生成时构造器形参的对象的run()方法
            //在创建一个线程
            Thread t2 = new Thread(i);
            t2.start();
        }
}
//实现Runnable接口实现多线程售票
class Window implements Runnable{
    int ticket = 100;

    public void run() {
        while(true){
            if(ticket > 0){
                System.out.println(Thread.currentThread().getName() + "出售票号:" + ticket--);
            }else{
                break;
            }
        }
    }
    
}

public class TestRunnableimpl {

    public static void main(String[] args) {
        Window w = new Window();
        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();
    }
}

 对比一下  继承的方式vs实现的方式

    1.联系:public class Thread implements Runnable

    2.哪个方式好?实现的方式优于继承的方式

      ①避免了java中单继承的局限性

      ②如果多个线程操作一份资源(数据),更适合使用实现的方式。

使用多线程的优点:

  1.提高应用程序的响应。对图形化界面更有意义,可增强用户体验。

  2.提高计算机系统CPU的利用率

  3.改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改

线程的分类:

  守护线程——java垃圾回收处理

  用户线程

线程的生命周期

 线程的安全问题:打印车票时,会出现重票、错票

  1.线程安全问题存在的原因?

    由于一个线程在操作共享数据过程中,为执行完毕的情况下,另外的线程参与进来,导致共享数据存在了安全问题。

  2.如何来解决线程的安全问题?

    必须让一个线程操作共享数据完毕以后,其他线程才有机会参与共享数据的操作。

  3.java如何实现线程的安全:线程的同步机制

    方式一:同步代码块

    synchronized(同步监视器){

      //需要被同步的代码块(即为操作共享数据的代码)

    }

    1.共享数据:多个线程共同操作的同一个数据(变量)

    2.同步监视器:由一个类的对象来充当。哪个线程获取此监视器。谁就执行大括号里被同步的代码。俗称:锁

    要求:所有的线程必须共用同一把锁!

    注:在实现的方式中,考虑同步的话,可以使用this来充当锁,但在继承的方式中,慎用this

//线程的同步机制——继承

class ThreadWindow extends Thread{
  static int ticket = 100;
  static Object obj = new Object();
  public void run(){
    while(true){
      synchronized (obj) {
        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 TestThread2 {
public static void main(String[] args) {
ThreadWindow tw1 = new ThreadWindow();
ThreadWindow tw2 = new ThreadWindow();
ThreadWindow tw3 = new ThreadWindow();

tw1.setName("窗口1");
tw2.setName("窗口2");
tw3.setName("窗口3");

tw1.start();
tw2.start();
tw3.start();
}
}


//线程的同步机制——实现
class
Window implements Runnable{ int ticket = 100;//共享数据 Animals a = new Animals(); public void run() { while (true) { synchronized (a) { 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--); } } } } } class Animals{ } public class TestRunnableimpl { public static void main(String[] args) { Window w = new Window(); 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(); } }

    方式二:同步方法

    将操作共享数据的方法声明为synchronized。即此方法为同步方法,能够保证当其中一个线程执行此方法时,其他线程在外等待直至此线程执行完此方法。

    >同步方法的锁:this

    注:1.对于非静态的方法而言,使用同步的话,默认锁为:this。如果使用在继承的方式实现多线程的话,慎用!

      2.对于静态的方法,如果使用同步,默认的锁为:当前类本身。以单例的懒汉式为例。Class clazz = Singleton.class 

    每个线程必须对应同一个锁(一个对象)。

    

class Window 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--);
        } 
    }
    
}
class Animals{
    
}
public class TestRunnableimpl {

    public static void main(String[] args) {
        Window w = new Window();
        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();
    }
}
关于懒汉式的线程安全问题,使用同步机制
//关于懒汉式的线程安全问题,使用同步机制
//对于一般的方法内,使用同步代码块,可以考虑使用this。
//对于静态方法而言,使用当前类本身充当锁。
class Singleton{
    private Singleton(){
        
    }
    private static Singleton instance = null;
    
    public static Singleton getInstance(){
        if(instance ==null){//给要抢夺资源的线程的提示,该资源已经被获取。
            synchronized (Singleton.class) {
                if(instance == null){
                    instance = new Singleton();
                }            
            }    
        }
        return instance;
    }
    
}
public class TestSingletion {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);
    }
}

释放锁的操作

  1.当前线程的同步方法、同步代码块执行结束。

  2.当前线程在同步代码块、同步方法中遇到break、return终止了该代码块、该方法的继续执行。

  3.当前线程在同步代码块、同步方法中出现了未处理的ErrorException,导致异常结束。

  4.当前线程在同步代码块、同步方法中执行了线程对象的wait()方法,当前线程暂停,并释放锁。

不会释放锁的操作

  1.线程执行同步代码块或同步方法时,程序调用Thread.sleep()、Thread.yield()方法暂停当前线程的执行

  2.线程执行同步代码块时,其他线程调用了该线程的suspend()方法将该线程挂起,该线程不会释放锁(同步监视器)。

 练习1:

  银行有一个账户。有两个储户分别向同一个账户存3000元,每次存1000元,存三次,每次存完,打印账户余额。

//继承的方式解决
class
Account1{ private double balance; public void Show(){ balance += 1000; System.out.print(Thread.currentThread().getName()); try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(balance); } } class Customer11 extends Thread{ Account1 account1 = null; public Customer11(Account1 account1) { this.account1 = account1; } public void run(){ synchronized (account1) { for(int i=0;i<3;i++){ account1.Show(); } } } } public class TestAccount1 { public static void main(String[] args) { Account1 account1 = new Account1(); Customer11 c1 = new Customer11(account1); Customer11 c2 = new Customer11(account1); Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); t1.setName("用户1"); t2.setName("用户2"); t1.start(); t2.start(); } }
//实现的方式解决

class Account{
private double balance;

public void SaveMoney(){
balance += 1000;
System.out.print(Thread.currentThread().getName() + "当前余额是:" );
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.balance);
}
}


class Customer implements Runnable{
private Account account = null;

public Customer() {


}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
Customer(Account account){
this.account = account;
}
public synchronized void run() {
for(int i=0;i<3;i++){
account.SaveMoney();
}
}

}



public class TestAccount {
public static void main(String[] args) {
Account accout = new Account();
Customer c1 = new Customer(accout);
Customer c2 = new Customer(accout);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.setName("用户1");
t2.setName("用户2");

t1.start();
t2.start();
}
}

多线程死锁

  出现的原因:多个线程都需要占用的资源被对方占有,并都不释放,线程阻塞。

public class ThreadTestX {
    static StringBuffer sb1 = new StringBuffer();
    static StringBuffer sb2 = new StringBuffer();
    
    public static void main(String[] args) {
        new Thread(){
            public void run(){
                synchronized (sb1) {
                    sb1.append("A");
                    try {
                        Thread.currentThread().sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (sb2) {
                        sb2.append("B");
                    }
                }
            }
        }.start();
        new Thread(){
            public void run(){
                synchronized (sb2) {
                    sb1.append("C");
                    try {
                        Thread.currentThread().sleep(10);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    synchronized (sb1) {
                        sb2.append("D");
                    }
                }
            }
        }.start();
        System.out.println(sb1);
        System.out.println(sb2);
        
    }
}

线程的通信

wait():

  令当前线程挂起并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问。

notify():

  唤醒正在排队等待同步资源的线程中优先级最高者结束等待

notifyAll():

  唤醒正在排队等待资源的所有线程结束等待。

在synchronized代码块中才能使用,否则报异常。

练习:实现二者交替的输出1-100

class Printnum1 implements Runnable{
    int num=1;
    public void run() {
        while(true){
            synchronized (this) {
                notify();
                try {
                    Thread.currentThread().sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }if(num<=100){
                    System.out.println(Thread.currentThread().getName() + ":" + num++);    
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                }else{
                    break;
                }
            }
        }
    }
}

public class PrintNum {
    public static void main(String[] args) {
        Printnum1 p1 = new Printnum1();
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p1);
        t1.setName("甲");
        t2.setName("乙");
        t1.start();
        t2.start();

    }
}

消费者-生产者问题:

class Clerk{//店员
    int product;//产品数量
    
    public synchronized void AddProduct(){//创建产品
        if(product >=20){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            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-- + "产品");
            notifyAll();
        }
    }
}


class Productor implements Runnable{//生产者
    Clerk clerk;

    public Productor(Clerk clerk) {
        super();
        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.AddProduct();
        }
    }
    
}
class Customer1 implements Runnable{//消费者
    Clerk clerk;
    public Customer1(Clerk clerk) {
        super();
        this.clerk = clerk;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("消费者消费产品");
        while(true){
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            clerk.ConsumeProduct();            
        }
    }
}


public class TestProductor {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Customer1 c = new Customer1(clerk);
        Productor p = new Productor(clerk);
        
        Thread c1 = new Thread(c);
        Thread c2 = new Thread(c);
        Thread p1 = new Thread(p);
        Thread p2 = new Thread(p);
        
        c1.setName("消费者1号");
        c2.setName("消费者2号");
        p1.setName("生产者1号");
        p2.setName("生产者2号");
    
        c1.start();
        c2.start();
        p1.start();
        p2.start();
    }
}
原文地址:https://www.cnblogs.com/yangHS/p/10678354.html