




已阅读5页,还剩32页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
目标:1、线程概念2、Thread3、Runnable4、线程的生命周期5、线程同步内容:1、线程概念:线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一般一个程序是由许多的线程组成。例如:一个程序中的动态时钟示例:在窗口中制作一个动态时钟package com.javaoo;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.table.*;import java.io.*;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Vector;public class TestTableAdvanced extends JFrame private Object columnNames = 学号, 姓名, 年龄, 性别;private Object rowData = s001, 张三, 23, 男,s002, 李四, 22, 男,s003, 王麻子, 21, 男;private DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);private JTable table = new JTable(tableModel);private JButton jbtSave = new JButton(Save);private JButton jbtClear = new JButton(Clear);private JButton jbtRestore = new JButton(Restore);private JButton jbtAddRow = new JButton(Add New Row);private JButton jbtAddColumn = new JButton(Add New Column);private JButton jbtDeleteRow = new JButton(Delete Selected Row);private JButton jbtDeleteColumn = new JButton(Delete Selected Column);private JLabel timeLabel = new JLabel();public TestTableAdvanced() super(JTable高级应用示例);setSize(400, 300);setDefaultCloseOperation(EXIT_ON_CLOSE);setResizable(false);setLocation();init();addListener();setVisible(true);public void init() JScrollPane scroll = new JScrollPane(table);getContentPane().add(scroll);JPanel p1 = new JPanel(); /存放Save,Clear,Restore按钮p1.add(jbtSave);p1.add(jbtClear);p1.add(jbtRestore);JPanel p2 = new JPanel(); /存放操作Table的功能按钮p2.setLayout(new GridLayout(2,2);p2.add(jbtAddRow);p2.add(jbtAddColumn);p2.add(jbtDeleteRow);p2.add(jbtDeleteColumn);JPanel p3 = new JPanel(); /窗口底部的大面板p3.setLayout(new GridLayout(2,1);p3.add(p1);p3.add(p2);getContentPane().add(p3, BorderLayout.SOUTH);JPanel p4 = new JPanel();p4.setLayout(new BorderLayout();p4.add(timeLabel, BorderLayout.EAST);getContentPane().add(p4, BorderLayout.NORTH);TimeRunning running = new TimeRunning();running.start();public void setLocation() Dimension d = this.getSize();int width = d.width;int height = d.height;Toolkit kit = this.getToolkit();int screenWidth = kit.getScreenSize().width;int screenHeight = kit.getScreenSize().height;this.setLocation(screenWidth - width) / 2, (screenHeight - height) / 2);public void addListener() jbtAddRow.addActionListener(new ActionListener() /匿名内部类实现按钮的监听public void actionPerformed(ActionEvent e) int index = table.getSelectedRow();if (index = 0) tableModel.insertRow(index, new Vector(); /在选择中行上新增数据 else tableModel.addRow(new Vector(); /在Table的末尾新增数据);jbtAddColumn.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) String name = JOptionPane.showInputDialog(输入列的名字:);tableModel.addColumn(name, new Vector(););jbtDeleteRow.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) int index = table.getSelectedRow();if (index = 0) tableModel.removeRow(index););jbtDeleteColumn.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) int index = table.getSelectedColumn();if (index = 0) TableColumnModel columnModel = table.getColumnModel();TableColumn tableColumn = columnModel.getColumn(index);columnModel.removeColumn(tableColumn););jbtSave.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) try ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tableModel.dat);out.writeObject(tableModel.getDataVector();out.writeObject(getColumnNames();out.close(); catch (IOException e1) e1.printStackTrace(););jbtRestore.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) try ObjectInputStream input = new ObjectInputStream(new FileInputStream(tableModel.dat);Vector rowData = (Vector) input.readObject();Vector columnNames = (Vector) input.readObject();tableModel.setDataVector(rowData, columnNames);input.close(); catch (Exception e1) e1.printStackTrace();); jbtClear.addActionListener(new ActionListener() public void actionPerformed(ActionEvent e) tableModel.setRowCount(0););private Vector getColumnNames() /获取Table表格中的所有列名Vector columnNames = new Vector();for (int i = 0; i table.getColumnCount(); i+) columnNames.add(table.getColumnName(i);return columnNames;class TimeRunning extends Thread /定义public void run() while (true) try SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);String s = sdf.format(new Date();timeLabel.setText(s);Thread.sleep(1000); catch (Exception e) e.printStackTrace();public static void main(String args) new TestTableAdvanced();2、进程与线程区分(1)一个在电脑上运行的程序(即:此程序已经在内存中),就是我们通常所说的进程。大部分操作系统都支持多进程并发运行。例如:一边写程序,一边听歌(2)线程就是在同一个进程中同时并发处理多个任务多线程编程优势第一:进程之间不能共享内存,线程可以第二:创建进程系统需要重新分配内存,但创建线程代价小得多,在多任务并发效率上线程的效率更高第三:Java内置多线程功能支持,简化了多线程编程3、Java中如何实现多线程(1)继承Thread类来完成多线程实现(2)实现Runnable接口来完成多线程实现4、Thread类应用(1)定义Thread类的子类(2)重写run方法(3)创建Thread类对象(4)启动线程class TimeRunning extends Thread /定义Thread类的子类public void run() while (true) try SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);String s = sdf.format(new Date();timeLabel.setText(s);Thread.sleep(1000); catch (Exception e) e.printStackTrace();TimeRunning r = new TimeRunning(); /实例化线程类对象r.start(); /启动线程两个重要的方法(1)返回当前线程的对象,Thread.currentThread()(2)返回当前线程的名字,getName()5、Runnable接口应用class TimeRunning implements Runnable public void run() while (true) try SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);String s = sdf.format(new Date();timeLabel.setText(s);Thread.sleep(1000); catch (Exception e) e.printStackTrace();Thread t = new Thread(new TimeRunning();t.start();示例:傻瓜式的摇奖程序(1)将号码放到奖池中(2)开始,奖池中的号码滚动(3)停止,号码滚动结束(4)弹出对话框,恭喜你中500万(5)实现线程停止和启动分析:(1)将号码保存到.properties文件中(要奖池)(2)学会读取.properties文件(3)停止或者启动,利用一个boolean来完成java.util.Properties(1)专门用于读取凡是以.properties结尾的文件(2)properties存储的文件必须是一个键值对方式存储Properties prop = new Properties(); /初始化Properties对象prop.load(new FileInputStream(perties);Enumeration enm = pertyNames(); /读取文件中的所有键while (enm.hasMoreElements() String key = (String)enm.nextElement(); /每个键 System.out.println(key); String value = prop.getProperty(key); /对应的值示例:分析整个程序会有几个线程在运行package com.javaoo;public class TestFirstThread extends Thread private int i;public void run() for (; i 100; i+) System.out.println(getName() + + i);public static void main(String args) for (int i = 0; i 100; i+) System.out.println(Thread.currentThread().getName() + + i);if (i = 20) new TestFirstThread().start();new TestFirstThread().start();6、线程的生命周期:线程的生命周期要经历5个状态(1)新建(2)就绪(3)运行(4)阻塞(5)死亡注意:线程一旦启动后,CPU本身会在多个线程之间进行切换。所以线程也会多次出现运行、阻塞之间切换7、线程池如果需要创建多个线程对象来执行一段代码,我们可以利用一个更加方便的方法来完成多线程工作,那就是线程池。示例:用一个例子哪种情况下使用线程池更加方便public PrintChar implements Runnable private char charToPrint;private int times;public PrintChar(char c, int t) charToPrint = c;times = t;public void run() for (int i = 0; i times; i+) System.out.print(charToPrint);public PrintNum implements Runnable private int lastNum;public PrintNum(int n) lastNum = n;public void run() for (int i = 1; i = lastNum; i+) System.out.print( + i);现在要求实现2个PrintChar线程和2个PrintNum线程,我们如何完成?大家可以参考如下的代码package com.javaoo;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Test /* * param args */public static void main(String args) /实现2个PrintChar和2个PrintNum线程Thread t1 = new Thread(new PrintChar(A, 50);Thread t2 = new Thread(new PrintChar(B, 50);Thread t3 = new Thread(new PrintNum(20);Thread t4 = new Thread(new PrintNum(10);t1.start();t2.start();t3.start();t4.start();8、Executor接口和ExecutorService接口JDK1.5版本以后提供了Executor接口在同一时间来管理多个线程包结构:java.util.concurrentExecutor接口中的方法(1)void execute(Runnable r)ExecutorService接口中的方法(1)void shutdown():关闭executor,但是存储在线程池中的线程对象还会继续执行,直到结束(2)List shutdownNow():关闭executor,且会马上停止未执行的线程对象,并将没有执行线程对象利用List返回(3)boolean isShutdown():判断executor是否关闭(4)boolean isTerminated():判断线程中的线程对象是否执行结束创建线程池,我们使用Executors来完成例如:(1)ExecutorService executor = Executors.newFixedThreadPool(3);(2)ExecutorService executor = Executors.newCachedThreadPool();完整的线程使用示例:public class TestExecutor public static void main(String args) ExecutorService executor = Executors.newFixedThreadPool(4); /可以存储管理4个线程对象executor.execute(new PrintChar(a, 50);executor.execute(new PrintChar(a, 50);executor.execute(new PrintNum(50);executor.execute(new PrintNum(50);executor.shutdown();9、线程同步(线程锁)线程同步主要是防止和解决多线程在使用共享资源时候发生冲突。示例:下面是多线程冲突的例子import java.util.concurrent.*;public class AccountWithoutSync private static Account account = new Account();public static void main(String args) ExecutorService executor = Executors.newCachedThreadPool();for (int i = 0; i 100; i+) executor.execute(new AddPennyTask();executor.shutdown();while(!executor.isTerminated() System.out.println(账号金额: + account.getBalance();/账号金额充值的线程类private static class AddPennyTask implements Runnable public void run() account.deposit(1); /存钱private static class Account /定义账号信息类private int balance = 0; /账户金额public int getBalance() return balance;public void deposit(int amount) int newBalance = balance + amount;try Thread.sleep(50); catch (InterruptedException e) balance = newBalance;上面的内容会出现账号金额不到100元的情况。但是理论上应该是100元,原因在于多线程发生冲突解决办法:(1)线程加同步锁一种语法public synchronized void deposit(int amount) (2)线程加同步锁的一种语法public void deposit(int amount) synchronized(this) 注意:线程同步加锁一定是针对对象来操作。上面加线程锁后的完整代码package com.javaoo;import java.util.concurrent.*;public class AccountWithoutSync private static Account account = new Account();public static void main(String args) ExecutorService executor = Executors.newCachedThreadPool();for (int i = 0; i 100; i+) executor.execute(new AddPennyTask();executor.shutdown();while(!executor.isTerminated() System.out.println(账号金额: + account.getBalance();/账号金额充值的线程类private static class AddPennyTask implements Runnable public void run() account.deposit(1);private static class Account private int balance = 0;public int getBalance() return balance;public void deposit(int amount) synchronized(this) int newBalance = balance + amount;try Thread.sleep(50); catch (InterruptedException e) balance = newBalance;作业:一个面包惹得祸?(面包师,面包,买面包的人)(1)当面包个数为10个,则面包师停止生产面包(2)当面包个数为0个,买面包的人开始排队等待(3)买面包的人每次
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 护理札记读后感:细节与本质的再思考
- 长江艺术工程职业学院《食工仪表自动化》2023-2024学年第二学期期末试卷
- 护理文件书写规范及要求
- 江苏省百校2024-2025学年高三下学期期初开学联考物理试题含解析
- 南充科技职业学院《中学生物课程资源开发与应用》2023-2024学年第二学期期末试卷
- 四川西南航空职业学院《化工热力学实验》2023-2024学年第二学期期末试卷
- 江苏航运职业技术学院《城乡空间分析与规划新技术》2023-2024学年第一学期期末试卷
- 中华女子学院《食品工厂设计概论》2023-2024学年第二学期期末试卷
- 十堰市茅箭区2024-2025学年小升初总复习数学测试题含解析
- 石家庄信息工程职业学院《FPGA数字系统课程设计》2023-2024学年第二学期期末试卷
- 北京市朝阳区2025届高三下学期一模试题 数学 含答案
- 运输公司安全管理制度
- 2025届江苏省扬州市中考一模语文试题(含答案)
- 2025年河北省唐山市中考一模道德与法治试题(含答案)
- 工程造价咨询服务投标方案(专家团队版-)
- 2024年广东省中考生物+地理试卷(含答案)
- 小小科学家《物理》模拟试卷A(附答案)
- 劳务派遣劳务外包服务方案(技术方案)
- 全尺寸测量报告FAI
- 燃气轮机原理概述及热力循环
- 限用物质清单AFIRM RSL(2019年年)34
评论
0/150
提交评论