201871010105-曹玉中《面向对象程序设计(java)》第十六周学习总结

项目 内容
这个作业属于哪个过程 https://www.cnblogs.com/nwnu-daizh/
这个作业的要求在哪里 https://www.cnblogs.com/zyja/p/11963340.html
作业学习目标

(1) 掌握Java应用程序的打包操作;

(2) 掌握线程概念;

(3) 掌握线程创建的两种技术。

第一部分:理论知识。

进程:指一个内存中运行的应用程序。例如运行QQ那么它就是一个进程,而且一个应用程序可以同时运行多个进程

线程:线程是进程中的一个执行单元,就比如用360我们可以让它一边杀毒一边清理垃圾,那么360它就是一个进程,那么杀毒和清理垃圾就是进程下的两个线程
注:一个程序运行后至少有一个进程,一个进程中可以包含多个线程

Thread类
构造方法:
public Thread() :分配一个新的线程对象。

public Thread(String name) :分配一个指定名字的新的线程对象。

public Thread(Runnable target) :分配一个带有指定目标新的线程对象。

public Thread(Runnable target,String name) :分配一个带有指定目标新的线程对象并指定名字。

常用方法:
public String getName() :获取当前线程名称。

public void start() :导致此线程开始执行; Java虚拟机调用此线程的run方法。

public void run() :此线程要执行的任务在此处定义代码。

public static void sleep(long millis) :使当前正在执行的线程以指定的毫秒数暂停

public static Thread currentThread() :返回对当前正在执行的线程对象的引用。

创建线程的方式总共有两种:
1.是继承Thread类方式
2.是实现Runnable接口

创建线程的方式一:

定义Thread类子类,并重写该类的run()方法,run()方法的方法体就代表了线程需要完成的任务,
创建Thread子类的实例3. 调用Thread的start()方法来启动该线程
代码如下:

  1. public class Test {
  2. public static void main(String[] args) {
  3. MyThread mt = new MyThread();
  4. Thread t1 = new Thread(mt);
  5. t1.start();
  6. }
  7. }
  8. class MyThread extends Thread{
  9. @Override
  10. public void run(){
  11. System.out.println("第一种方式创建线程");
  12. }
  13. }

创建线程的方式二:

定义Runnable接口的实现类,并重写该接口的run()方法,run()方法的方法体代表线程完成的任务
创建Runnable实现类的实例。
调用Thread的start()方法来启动线程。
代码如下:

  1. public class Test {
  2. public static void main(String[] args) {
  3. MyRunnable mr = new MyRunnable();
  4. Thread t1 = new Thread(mr);
  5. t1.start();
  6. }
  7. }
  8. class MyRunnable implements Runnable{
  9. @Override
  10. public void run(){
  11. System.out.println("第二种方式创建线程");
  12. }
  13. }

Thread和Runnable的区别
因为类都是单继承的,如果一个类继承Thread,就不可以继承其他类了。但是如果实现了Runnable接口的话,则很容易的实现资源共享,避免了java中的单继承的局限性,所以Runnable比Thread更有优势

用匿名内部类创建线程
使用匿名内部类的方式实现Runnable接口,重写Runnable接口中的run方法:

代码如下:

  1. public class Test {
  2. public static void main(String[] args) {
  3. new Thread(new Runnable(){
  4. @Override
  5. public void run() {
  6. System.out.println("匿名内部类创建线程");
  7. }
  8. }).start();
  9. }
  10. }

线程安全问题的概述
如果有多个线程在同时运行,而这些线程可能会同时运行这段代码。程序每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。
那么什么是线程不安全的呢?我们由一段代码看一下:
这里我想打印的是1-100之间的整数:

  1. public class Test {
  2. public static void main(String[] args) {
  3. MyRunnable r = new MyRunnable();
  4. Thread t1 = new Thread(r);
  5. Thread t2 = new Thread(r);
  6. Thread t3 = new Thread(r);
  7. t1.start();
  8. t2.start();
  9. t3.start();
  10. }
  11. }
  12. class MyRunnable implements Runnable{
  13. private int sum = ;
  14. public void run(){
  15. while(true){
  16. if(sum>){
  17. try {
  18. Thread.sleep();
  19. catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. System.out.println(sum);
  23. sum--;
  24. }
  25. }
  26. }
  27. }

运行结果出现了很多重复的,甚至还有-1,结果和预期是不一样的,这就是线程不安全情况。那么为什么会出现这种情况呢?是因为这三个线程在执行过程中不断抢夺CPU的执行权,当某一个线程运行到Thread.sleep(10)的时候处于睡眠状态,那么CPU的执行权交给了另外两个线程以此类推,三个线程都执行到了这里,这时代码就不是一条判断一条输出了,当睡眠结束后三条线程面临的都是一条输出语句一个sum–不再判断sum的值,若最后判断sum的值为1,最后sum的值将被–三次,所以才会导致最终的结果出现0和-1的情况(最终sum的值为-2),这里的Thread.sleep()其实是为了增加线程安全问题出现的概率。
第二部分:实验。

测试程序1

elipse IDE中调试运行教材585页程序13-1,结合程序运行结果理解程序;

将所生成的JAR文件移到另外一个不同的目录中,再运行该归档文件,以便确认程序是从JAR文件中,而不是从当前目录中读取的资源。

掌握创建JAR文件的方法;

代码如下:

  1. package resource;
  2.  
  3. import java.awt.*;
  4. import java.io.*;
  5. import java.net.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.  
  9. /**
  10. * @version 1.41 2015-06-12
  11. * @author Cay Horstmann
  12. */
  13. public class ResourceTest
  14. {
  15. public static void main(String[] args)
  16. {
  17. EventQueue.invokeLater(() -> {
  18. JFrame frame = new ResourceTestFrame();
  19. frame.setTitle("ResourceTest");
  20. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21. frame.setVisible(true);
  22. });
  23. }
  24. }
  25.  
  26. /**
  27. * A frame that loads image and text resources.
  28. */
  29. class ResourceTestFrame extends JFrame
  30. {
  31. private static final int DEFAULT_WIDTH = ;
  32. private static final int DEFAULT_HEIGHT = ;
  33.  
  34. public ResourceTestFrame()
  35. {
  36. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
  37. URL aboutURL = getClass().getResource("about.gif");
  38. Image img = new ImageIcon(aboutURL).getImage();
  39. setIconImage(img);
  40.  
  41. JTextArea textArea = new JTextArea();
  42. InputStream stream = getClass().getResourceAsStream("about.txt");
  43. try (Scanner in = new Scanner(stream, "UTF-8"))
  44. {
  45. while (in.hasNext())
  46. textArea.append(in.nextLine() + "\n");
  47. }
  48. add(textArea);
  49. }
  50. }
  1. Main-Class: resource.ResourceTest

Core Java: Fundamentals
10th Edition
Cay Horstmann and Gary Cornell
Copyright 漏 2016
Prentice-Hall

运行结果如下:

测试程序2:

l 在elipse IDE中调试运行ThreadTest,结合程序运行结果理解程序;

l 掌握线程概念;

l 掌握用Thread的扩展类实现线程的方法;

l 利用Runnable接口改造程序,掌握用Runnable接口创建线程的方法。

代码如下:

  1. class Lefthand extends Thread {
  2. public void run()
  3. {
  4. for(int i=;i<=;i++)
  5. { System.out.println("You are Students!");
  6. try{ sleep(); }
  7. catch(InterruptedException e)
  8. { System.out.println("Lefthand error.");}
  9. }
  10. }
  11. }
  12. class Righthand extends Thread {
  13. public void run()
  14. {
  15. for(int i=;i<=;i++)
  16. { System.out.println("I am a Teacher!");
  17. try{ sleep(); }
  18. catch(InterruptedException e)
  19. { System.out.println("Righthand error.");}
  20. }
  21. }
  22. }
  23. public class ThreadTest
  24. {
  25. static Lefthand left;
  26. static Righthand right;
  27. public static void main(String[] args)
  28. { left=new Lefthand();
  29. right=new Righthand();
  30. left.start();
  31. right.start();
  32. }
  33. }

运行结果如下:

Runnable接口创建线程的方法

  1. class Lefthand implements Runnable {
  2. public void run() {
  3. for (int i = ; i <= ; i++) {
  4. System.out.println("You are Students!");
  5. try {
  6. Thread.sleep();
  7. } catch (InterruptedException e) {
  8. System.out.println("Lefthand error.");
  9. }
  10. }
  11. }
  12. }
  13.  
  14. class Righthand implements Runnable {
  15. public void run() {
  16. for (int i = ; i <= ; i++) {
  17. System.out.println("I am a Teacher!");
  18. try {
  19. Thread.sleep();
  20. } catch (InterruptedException e) {
  21. System.out.println("Righthand error.");
  22. }
  23. }
  24. }
  25. }
  26.  
  27. public class ThreadTest {
  28. public static void main(String[] args) {
  29. Runnable left = new Lefthand();
  30. Thread a = new Thread(left);
  31. Runnable right = new Righthand();
  32. Thread b = new Thread(right);
  33. a.start();
  34. b.start();
  35. }
  36. }

运行结果如下:

测试程序3:

在Elipse环境下调试教材625页程序14-1、14-2 、14-3,结合程序运行结果理解程序;

代码如下:

  1. package bounceThread;
  2.  
  3. import java.awt.geom.*;
  4.  
  5. /**
  6. A ball that moves and bounces off the edges of a
  7. rectangle
  8. * @version 1.33 2007-05-17
  9. * @author Cay Horstmann
  10. */
  11. public class Ball
  12. {
  13. private static final int XSIZE = ;
  14. private static final int YSIZE = ;
  15. private double x = ;
  16. private double y = ;
  17. private double dx = ;
  18. private double dy = ;
  19.  
  20. /**
  21. Moves the ball to the next position, reversing direction
  22. if it hits one of the edges
  23. */
  24. //定义了移动方法
  25. public void move(Rectangle2D bounds)
  26. {
  27. x += dx;
  28. y += dy;
  29. if (x < bounds.getMinX())
  30. {
  31. x = bounds.getMinX();
  32. dx = -dx;
  33. }
  34. if (x + XSIZE >= bounds.getMaxX())
  35. {
  36. x = bounds.getMaxX() - XSIZE;
  37. dx = -dx;
  38. }
  39. if (y < bounds.getMinY())
  40. {
  41. y = bounds.getMinY();
  42. dy = -dy;
  43. }
  44. if (y + YSIZE >= bounds.getMaxY())
  45. {
  46. y = bounds.getMaxY() - YSIZE;
  47. dy = -dy;
  48. }
  49. }
  50.  
  51. /**
  52. Gets the shape of the ball at its current position.
  53. */
  54. //定义球外形
  55. public Ellipse2D getShape()
  56. {
  57. return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
  58. }
  59. }
  1. package bounceThread;
  2.  
  3. import java.awt.geom.*;
  4.  
  5. /**
  6. A ball that moves and bounces off the edges of a
  7. rectangle
  8. * @version 1.33 2007-05-17
  9. * @author Cay Horstmann
  10. */
  11. public class Ball
  12. {
  13. private static final int XSIZE = ;
  14. private static final int YSIZE = ;
  15. private double x = ;
  16. private double y = ;
  17. private double dx = ;
  18. private double dy = ;
  19.  
  20. /**
  21. Moves the ball to the next position, reversing direction
  22. if it hits one of the edges
  23. */
  24. //定义了移动方法
  25. public void move(Rectangle2D bounds)
  26. {
  27. x += dx;
  28. y += dy;
  29. if (x < bounds.getMinX())
  30. {
  31. x = bounds.getMinX();
  32. dx = -dx;
  33. }
  34. if (x + XSIZE >= bounds.getMaxX())
  35. {
  36. x = bounds.getMaxX() - XSIZE;
  37. dx = -dx;
  38. }
  39. if (y < bounds.getMinY())
  40. {
  41. y = bounds.getMinY();
  42. dy = -dy;
  43. }
  44. if (y + YSIZE >= bounds.getMaxY())
  45. {
  46. y = bounds.getMaxY() - YSIZE;
  47. dy = -dy;
  48. }
  49. }
  50.  
  51. /**
  52. Gets the shape of the ball at its current position.
  53. */
  54. //定义球外形
  55. public Ellipse2D getShape()
  56. {
  57. return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
  58. }
  59. }
  1. package bounce;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  6.  
  7. /**
  8. * Shows an animated bouncing ball.
  9. * @version 1.34 2015-06-21
  10. * @author Cay Horstmann
  11. */
  12. public class Bounce
  13. {
  14. public static void main(String[] args)
  15. {
  16. EventQueue.invokeLater(() -> {
  17. JFrame frame = new BounceFrame();
  18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  19. frame.setVisible(true);
  20. });
  21. }
  22. }
  23.  
  24. /**
  25. * The frame with ball component and buttons.
  26. */
  27. class BounceFrame extends JFrame
  28. {
  29. private BallComponent comp;
  30. public static final int STEPS = ;
  31. public static final int DELAY = ;
  32.  
  33. /**
  34. * Constructs the frame with the component for showing the bouncing ball and
  35. * Start and Close buttons
  36. */
  37. public BounceFrame()
  38. {
  39. setTitle("Bounce");
  40. comp = new BallComponent();
  41. add(comp, BorderLayout.CENTER);
  42. JPanel buttonPanel = new JPanel();
  43. addButton(buttonPanel, "Start", event -> addBall());//将按钮放入buttonPanel
  44. addButton(buttonPanel, "Close", event -> System.exit());
  45. add(buttonPanel, BorderLayout.SOUTH);//将buttonPanel放入边界管理器的南端
  46. pack();
  47. }
  48.  
  49. /**
  50. * Adds a button to a container.
  51. * @param c the container
  52. * @param title the button title
  53. * @param listener the action listener for the button
  54. */
  55. public void addButton(Container c, String title, ActionListener listener)
  56. {
  57. //生成按钮对象
  58. JButton button = new JButton(title);
  59. c.add(button);
  60. button.addActionListener(listener);//注册监听器事件
  61. }
  62.  
  63. /**
  64. * Adds a bouncing ball to the panel and makes it bounce 1,000 times.
  65. */
  66. public void addBall()
  67. {
  68. try
  69. {
  70. Ball ball = new Ball();
  71. comp.add(ball);
  72.  
  73. for (int i = ; i <= STEPS; i++)
  74. {
  75. ball.move(comp.getBounds());
  76. comp.paint(comp.getGraphics());
  77. Thread.sleep(DELAY);//在两个球显示之间有延迟
  78. }
  79. }
  80. catch (InterruptedException e)//中断异常
  81. {
  82. }
  83. }
  84. }
  85.  
  86. Bounce
  87.  
  88. Bounce

运行结果如下:

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

l 对比两个程序,理解线程的概念和用途;

l 掌握线程创建的两种技术。

代码如下:

  1. package bounceThread;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.*;
  5.  
  6. import javax.swing.*;
  7.  
  8. /**
  9. * 显示动画弹跳球
  10. * @version 1.34 2015-06-21
  11. * @author Cay Horstmann
  12. */
  13. public class BounceThread {
  14. public static void main(String[] args) {
  15. EventQueue.invokeLater(() -> {
  16. JFrame frame = new BounceFrame();
  17. frame.setTitle("BounceThread");
  18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  19. frame.setVisible(true);
  20. });
  21. }
  22. }
  23.  
  24. /**
  25. * 框架与球组件和按钮
  26. */
  27. class BounceFrame extends JFrame {
  28. private BallComponent comp;
  29. public static final int STEPS = ;
  30. public static final int DELAY = ;
  31.  
  32. /**
  33. * 用显示弹跳球以及开始和关闭按钮的组件构建框架
  34. */
  35. public BounceFrame() {
  36. comp = new BallComponent();
  37. add(comp, BorderLayout.CENTER);
  38. JPanel buttonPanel = new JPanel();
  39. addButton(buttonPanel, "Start", event -> addBall());
  40. addButton(buttonPanel, "Close", event -> System.exit());
  41. add(buttonPanel, BorderLayout.SOUTH);
  42. pack();
  43. }
  44.  
  45. /**
  46. * 向容器添加按钮
  47. *
  48. * @param c
  49. * the container
  50. * @param title
  51. * the button title
  52. * @param listener
  53. * the action listener for the button
  54. */
  55. public void addButton(Container c, String title, ActionListener listener) {
  56. JButton button = new JButton(title);
  57. c.add(button);
  58. button.addActionListener(listener);
  59. }
  60.  
  61. /**
  62. * 在画布上添加一个弹跳球,并启动一个线程使其弹跳
  63. */
  64. public void addBall() {
  65. Ball ball = new Ball();
  66. comp.add(ball);
  67. Runnable r = () -> {
  68. try {
  69. for (int i = ; i <= STEPS; i++) {
  70. ball.move(comp.getBounds());//将球移动到下一个位置,如果碰到其中一个边缘则反转方向
  71. comp.repaint();//重绘此组件。
  72. Thread.sleep(DELAY);//在指定的毫秒数内让当前正在执行的线程休眠
  73. }
  74. } catch (InterruptedException e) {
  75. }
  76. };
  77. Thread t = new Thread(r);
  78. t.start();
  79. }
  80. }

运行结果如下:

第三部分:学习总结

通过本章的学习,掌握了一些关于线程的相关知识,在学习的时候学的一片混乱,好在课下通过看书

和在Mooc上 看翁凯老师的课才对本章内容有了一定的了解,但还需要再做一些练习才能够掌握本章内容

的精髓,在做验证性实验部分内容的时候,并没有遇到很多困难,同时体验到了本章实验内容的重要性,

但实验课的时候遇到较多问题,好在在助教学长的帮助下得以解决,我也会在课下多多学习,加强巩固

基础知识。

201871010105-曹玉中《面向对象程序设计(java)》第十六周学习总结的更多相关文章

  1. 201571030332 扎西平措 《面向对象程序设计Java》第八周学习总结

    <面向对象程序设计Java>第八周学习总结   项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https: ...

  2. 201771010118马昕璐《面向对象程序设计java》第八周学习总结

    第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...

  3. 201771010134杨其菊《面向对象程序设计java》第八周学习总结

    第八周学习总结 第一部分:理论知识 一.接口.lambda和内部类:  Comparator与comparable接口: 1.comparable接口的方法是compareTo,只有一个参数:comp ...

  4. 201771010134杨其菊《面向对象程序设计java》第七周学习总结

    第七周学习总结 第一部分:理论知识 1.继承是面向对象程序设计(Object Oriented Programming-OOP)中软件重用的关键技术.继承机制使用已经定义的类作为基础建立新的类定义,新 ...

  5. 201771010123汪慧和《面向对象程序设计JAVA》第六周实验总结

    一.理论部分: 1.继承 用已有类来构建新类的一种机制.当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况. 2.类.超类.子类 (1)类继承 ...

  6. 201771010128 王玉兰《面象对象程序设计 (Java) 》第六周学习总结

    ---恢复内容开始--- 第一部分:基础知识总结: 1.继承 A:用已有类来构建新类的一种机制,当定义了一个新类继承一个类时,这个新类就继承了这个类的方法和域以适应新的情况: B:特点:具有层次结构. ...

  7. 周强201771010141《面向对象程序设计Java》第八周学习总结

    一.理论知识学习部分 Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个接口. 接口体中包含常量定义和方法定义,接口中只进行方法的声明,不提供方法的实现. 类似建立类的继承关系 ...

  8. 201871010126 王亚涛《面向对象程序设计 JAVA》 第十三周学习总结

      内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/ ...

  9. 马凯军201771010116《面向对象程序设计Java》第八周学习总结

    一,理论知识学习部分 6.1.1 接口概念 两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构:二,一个类所具有的方法的特征集合,是一种逻辑上的抽象.前者叫做“Java接口”,后 ...

  10. 201777010217-金云馨《面向对象程序设计Java》第八周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

随机推荐

  1. aiohttp_spider

    aiohttp_spider_def: import asyncio import re import aiohttp import aiomysql from pyquery import PyQu ...

  2. input 控件常用属性

  3. 201871010113-刘兴瑞《面向对象程序设计(java)》第四周学习总结

    项目 内容 这个作业属于哪个课程 <任课教师博客主页链接>https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 <作业链接地址>http ...

  4. 《京东到家订单中心 Elasticsearch 演进历程》----阅读

    上篇通过阅读文章对京东到家的架构分析有了初步了解,这次对文章(https://mp.weixin.qq.com/s?__biz=MzU1MzE2NzIzMg==&mid=2247486889& ...

  5. layui中form表单渲染的问题

    layui 官网的这部分文档介绍:http://www.layui.com/doc/modules/form.html#render 注意:针对的是表单元素,input select  textare ...

  6. 端口转发之 nc

    nc使用方法: Ncat 7.50 ( https://nmap.org/ncat ) Usage: ncat [options] [hostname] [port] Options taking a ...

  7. Nginx+Tomcat+Memcache 实现session共享

    Nginx + Tomcat + Memcache 实现session共享 1. Nginx 部署 1.上传源码包到服务器,解压安装 下载地址:http://nginx.org/en/download ...

  8. centos6利用cgroup冻结一个程序运行

    操作步骤: 安装cgroup服务 yum install libcgroup 配置cgroup vim /etc/cgconfig.conf group stopit{ #添加一个cgroup组 fr ...

  9. [Zabbix] 安装MySQL5.7, 部署Zabbix到CentOS 7日记

    安装环境:CentOS7 64位,安装MySQL5.7 一.安装 MySQL 1.配置YUM源 在MySQL官网中下载YUM源rpm安装包:http://dev.mysql.com/downloads ...

  10. 千万级MySQL数据库建立索引,提高性能的秘诀

    实践中如何优化MySQL 实践中,MySQL的优化主要涉及SQL语句及索引的优化.数据表结构的优化.系统配置的优化和硬件的优化四个方面,如下图所示: SQL语句及索引的优化 SQL语句的优化 SQL语 ...