zoukankan      html  css  js  c++  java
  • 达拉草201771010105《面向对象程序设计(java)》第十七周学习总结

    达拉草201771010105《面向对象程序设计(java)》第十七周学习总结

    第一部分:理论知识

    1.多线程的概念:

    (1)多线程是进程执行过程中产生的多条执行线索。 

    (2)多线程意味着一个程序的多行语句可以看上去几 乎在同一时间内同时运行。 

    (3)线程不能独立存在,必须存在于进程中,同一进 程的各线程间共享进程空间的数据。 

    Java实现多线程有两种途径:
    创建Thread类的子类
    在程序中定义实现Runnable接口的类

    用Thread类的子类创建线程:

    (1)首先需从Thread类派生出一个子类,在该子类中 重写run()方法。 

    例: class hand extends Thread {

    public void run() {……}

    }

    (2) 然后用创建该子类的对象 

    Lefthand left=new Lefthand();

    Righthand right=new Righthand(); 

    (3)最后用start()方法启动线程 

    left.start();

    right.start();

    用Thread类的子类创建多线程的关键性操作:

    (1)定义Thread类的子类并实现用户线程操作,即 run()方法的实现。

    (2)在适当的时候启动线程。

    由于Java只支持单重继承,用这种方法定义的类不 可再继承其他父类。

    用Runnable()接口实现线程

    (1)首先设计一个实现Runnable接口的类; 

    (2) 然后在类中根据需要重写run方法; 

    (3)再创建该类对象,以此对象为参数建立Thread 类的对象; 

    (4)调用Thread类对象的start方法启动线程,将 CPU执行权转交到run方法。

    被阻塞线程和等待线程

     blocked (被阻塞):

    阻塞时线程不能进入队列排队,必须等到引起 阻塞的原因消除,才可重新进入排队队列。 

    sleep(),wait()是两个常用引起线程阻塞的方法。

    线程阻塞的三种情况:

    (1)等待阻塞 :通过调用线程的wait()方法,让线 程等待某工作的完成。 

    (2)同步阻塞 :线程在获取synchronized同步锁失 败(因为锁被其它线程所占用),它会进入同步阻 塞状态。 

    (3)其他阻塞 :通过调用线程的sleep()或join() 或发出了I/O请求时,线程会进入到阻塞状态。当 sleep()状态超时、join()等待线程终止或者超 时、或者I/O处理完毕时,线程重新转入就绪状态。

    被终止的线程

     Terminated (被终止) 线程被终止的原因有二: 

    (1)一是run()方法中最后一个语句执行完毕而自 然死亡。 

    (2)二是因为一个没有捕获的异常终止了run方法 而意外死亡。 

    可以调用线程的stop 方 法 杀 死 一 个 线 程 (thread.stop();),但是,stop方法已过时, 不要在自己的代码中调用它。

    其他判断和影响线程状态的方法:

    (1)join():等待指定线程的终止。 

    (2)join(long millis):经过指定时间等待终止指定 的线程。 

    (3)isAlive():测试当前线程是否在活动。 

    (4)yield():让当前线程由“运行状态”进入到“就 绪状态”,从而让其它具有相同优先级的等待线程 获取执行权。

    多线程调度

    (1)Java提供一个线程调度器来监控程序启动后进入可运行状态的所有线程。线程调度器按照线程的优先级决定应调度哪些线程来执行。

    (2)处于可运行状态的线程首先进入就绪队列排队等候处理器资源,同一时刻在就绪队列中的线程可能有多个。Java的多线程系统会给每个线程自动分配一个线程的优先级。

     Java 的线程调度采用优先级策略:

    (1)优先级高的先执行,优先级低的后执行;

    (2)多线程系统会自动为每个线程分配一个优先级,缺省时,继承其父类的优先级;

    (3)任务紧急的线程,其优先级较高;

    (4)同优先级的线程按“先进先出”的队列原则;

    守护线程

    守护线程的惟一用途是为其他线程提供服务。例 如计时线程。

    在一个线程启动之前,调用setDaemon方法可 将线程转换为守护线程(daemon thread)。 例如: setDaemon(true);

    实验十七  线程同步控制

    实验时间 2018-12-10

    1、实验目的与要求

    (1) 掌握线程同步的概念及实现技术;

    (2) 线程综合编程练习

    2、实验内容和步骤

    实验1:测试程序并进行代码注释。

    测试程序1:

    l  在Elipse环境下调试教材651页程序14-7,结合程序运行结果理解程序;

    l  掌握利用锁对象和条件对象实现的多线程同步技术。

    package synch;
    
    import java.util.*;
    import java.util.concurrent.locks.*;
    
    /**
     * A bank with a number of bank accounts that uses locks for serializing access.
     * @version 1.30 2004-08-01
     * @author Cay Horstmann
     */
    public class Bank
    {
       private final double[] accounts;
       private Lock bankLock;
       private Condition sufficientFunds;
    
       /**
        * Constructs the bank.
        * @param n the number of accounts
        * @param initialBalance the initial balance for each account
        */
       public Bank(int n, double initialBalance)
       {
          accounts = new double[n];
          Arrays.fill(accounts, initialBalance);
          bankLock = new ReentrantLock();
          sufficientFunds = bankLock.newCondition();
       }
    
       /**
        * Transfers money from one account to another.
        * @param from the account to transfer from
        * @param to the account to transfer to
        * @param amount the amount to transfer
        */
       public void transfer(int from, int to, double amount) throws InterruptedException//当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常。
       {
          bankLock.lock();//加锁
          try
          {
             while (accounts[from] < amount)//条件对象判断当前对象是否进入
                sufficientFunds.await();//造成当前线程在接到信号或被中断之前一直处于等待状态。
             System.out.print(Thread.currentThread());
             accounts[from] -= amount;
             System.out.printf(" %10.2f from %d to %d", amount, from, to);
             accounts[to] += amount;
             System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
             sufficientFunds.signalAll();
          }
          finally
          {
             bankLock.unlock();//释放锁
          }
       }
    
       /**
        * Gets the sum of all account balances.
        * @return the total balance
        */
       public double getTotalBalance()
       {
          bankLock.lock();
          try
          {
             double sum = 0;
    
             for (double a : accounts)
                sum += a;
    
             return sum;
          }
          finally
          {
             bankLock.unlock();
          }
       }
    
       /**
        * Gets the number of accounts in the bank.
        * @return the number of accounts
        */
       public int size()
       {
          return accounts.length;
       }
    }
    package synch;
    
    /**
     * This program shows how multiple threads can safely access a data structure.
     * @version 1.31 2015-06-21
     * @author Cay Horstmann
     */
    public class SynchBankTest
    {
       public static final int NACCOUNTS = 100;
       public static final double INITIAL_BALANCE = 1000;
       public static final double MAX_AMOUNT = 1000;
       public static final int DELAY = 10;
       
       public static void main(String[] args)
       {
          Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
          for (int i = 0; i < NACCOUNTS; i++)
          {
             int fromAccount = i;
             Runnable r = () -> {
                try
                {
                   while (true)
                   {
                      int toAccount = (int) (bank.size() * Math.random());
                      double amount = MAX_AMOUNT * Math.random();
                      bank.transfer(fromAccount, toAccount, amount);
                      Thread.sleep((int) (DELAY * Math.random()));
                   }
                }
                catch (InterruptedException e)
                {
                }            
             };
             Thread t = new Thread(r);
             t.start();
          }
       }
    }

    运行结果如下:

    测试程序2:

    l  在Elipse环境下调试教材655页程序14-8,结合程序运行结果理解程序;

    l  掌握synchronized在多线程同步中的应用。

    package synch2;
    
    import java.util.*;
    
    /**
     * A bank with a number of bank accounts that uses synchronization primitives.
     * @version 1.30 2004-08-01
     * @author Cay Horstmann
     */
    public class Bank
    {
       private final double[] accounts;
    
       /**
        * Constructs the bank.
        * @param n the number of accounts
        * @param initialBalance the initial balance for each account
        */
       public Bank(int n, double initialBalance)
       {
          accounts = new double[n];
          Arrays.fill(accounts, initialBalance);
       }
    
       /**
        * Transfers money from one account to another.
        * @param from the account to transfer from
        * @param to the account to transfer to
        * @param amount the amount to transfer
        */
       public synchronized void transfer(int from, int to, double amount) throws InterruptedException
       {
          while (accounts[from] < amount)
             wait();
          System.out.print(Thread.currentThread());
          accounts[from] -= amount;
          System.out.printf(" %10.2f from %d to %d", amount, from, to);
          accounts[to] += amount;
          System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
          notifyAll();
       }
    
       /**
        * Gets the sum of all account balances.
        * @return the total balance
        */
       public synchronized double getTotalBalance()
       {
          double sum = 0;
    
          for (double a : accounts)
             sum += a;
    
          return sum;
       }
    
       /**
        * Gets the number of accounts in the bank.
        * @return the number of accounts
        */
       public int size()
       {
          return accounts.length;
       }
    }
    package synch2;
    
    /**
     * This program shows how multiple threads can safely access a data structure,
     * using synchronized methods.
     * @version 1.31 2015-06-21
     * @author Cay Horstmann
     */
    public class SynchBankTest2
    {
       public static final int NACCOUNTS = 100;
       public static final double INITIAL_BALANCE = 1000;
       public static final double MAX_AMOUNT = 1000;
       public static final int DELAY = 10;
    
       public static void main(String[] args)
       {
          Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
          for (int i = 0; i < NACCOUNTS; i++)
          {
             int fromAccount = i;
             Runnable r = () -> {
                try
                {
                   while (true)
                   {
                      int toAccount = (int) (bank.size() * Math.random());
                      double amount = MAX_AMOUNT * Math.random();
                      bank.transfer(fromAccount, toAccount, amount);
                      Thread.sleep((int) (DELAY * Math.random()));
                   }
                }
                catch (InterruptedException e)
                {
                }
             };
             Thread t = new Thread(r);
             t.start();
          }
       }
    }

    运行结果如下:

    测试程序3:

    l  在Elipse环境下运行以下程序,结合程序运行结果分析程序存在问题;

    l  尝试解决程序中存在问题。

    class Cbank

    {

         private static int s=2000;

         public   static void sub(int m)

         {

               int temp=s;

               temp=temp-m;

              try {

                         Thread.sleep((int)(1000*Math.random()));

                       }

               catch (InterruptedException e)  {              }

                     s=temp;

                     System.out.println("s="+s);

                 }

    }

     

     

    class Customer extends Thread

    {

      public void run()

      {

       for( int i=1; i<=4; i++)

         Cbank.sub(100);

        }

     }

    public class Thread3

    {

     public static void main(String args[])

      {

       Customer customer1 = new Customer();

       Customer customer2 = new Customer();

       customer1.start();

       customer2.start();

      }

    }

    class Cbank
    {
         private static int s=2000;
         public   static void sub(int m)
         {
               int temp=s;
               temp=temp-m;
              try {
                     Thread.sleep((int)(1000*Math.random()));
                   }
               catch (InterruptedException e)  {              }
                  s=temp;
                  System.out.println("s="+s);
              }
        }
    
    
    class Customer extends Thread
    {
      public void run()
      {
       for( int i=1; i<=4; i++)
         Cbank.sub(100);
        }
     }
    public class Thread3
    {
     public static void main(String args[])
      {
       Customer customer1 = new Customer();
       Customer customer2 = new Customer();
       customer1.start();
       customer2.start();
      }
    }

    运行结果如下:

    改进后的程序如下:

    class Cbank
    {
         private static int s=2000;
         public synchronized static void sub(int m)
         {
               int temp=s;
               temp=temp-m;
              try {
                     Thread.sleep((int)(1000*Math.random()));
                   }
               catch (InterruptedException e)  {              }
                  s=temp;
                  System.out.println("s="+s);
              }
        }
    
    
    class Customer extends Thread
    {
      public void run()
      {
       for( int i=1; i<=4; i++)
         Cbank.sub(100);
        }
     }
    public class Thread3
    {
     public static void main(String args[])
      {
       Customer customer1 = new Customer();
       Customer customer2 = new Customer();
       customer1.start();
       customer2.start();
      }
    }

    运行结果如下:

    实验2 编程练习

    利用多线程及同步方法,编写一个程序模拟火车票售票系统,共3个窗口,卖10张票,程序输出结果类似(程序输出不唯一,可以是其他类似结果)。

    Thread-0窗口售:第1张票

    Thread-0窗口售:第2张票

    Thread-1窗口售:第3张票

    Thread-2窗口售:第4张票

    Thread-2窗口售:第5张票

    Thread-1窗口售:第6张票

    Thread-0窗口售:第7张票

    Thread-2窗口售:第8张票

    Thread-1窗口售:第9张票

    Thread-0窗口售:第10张票

     

    public class Demo {
        public static void main(String[] args) {
        mythread mythread=new mythread();
        Thread t1=new Thread(mythread);
        Thread t2=new Thread(mythread);
        Thread t3=new Thread(mythread);
        t1.start();
        t2.start();
        t3.start();
    }
    }
    class mythread implements Runnable{
        int t=1;
        boolean flag=true;
        @Override
        public void run() {
            while(flag) {
                try {
                    Thread.sleep(50);
                }catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
                synchronized (this) {
                if(t<=10) {
            // TODO Auto-generated method stub
                     System.out.println(Thread.currentThread().getName() + "窗口售:第" + t + "张票");
                     t++;
                }
                if(t>10) {
                    flag=false;
                }
                }
            }
        
        }
        
    }

    运行结果如下:

    实验总结:

           本周学习了同步线程的相关问题,这也是我们最后一次实验,在这周的学习中我们学习了并发多线程,学习了锁对象、synchronized关键字等。

  • 相关阅读:
    java strtus2 拦截器(Interceptors)
    java ssm框架入门(三)正式项目的web.xml配置
    java Web监听器导图详解
    java web hello world(二)基于Servlet理解监听
    java ssm框架入门(二)添加语言滤器
    java web 自定义filter
    Java内存分配全面浅析
    Velocity !$ 和$!区别
    spring ioc原理(看完后大家可以自己写一个spring)
    Spring的AOP简单理解
  • 原文地址:https://www.cnblogs.com/dalacao/p/10163378.html
Copyright © 2011-2022 走看看