多线程·线程间通信 和 GUI

单例设计模式

* A:单例设计模式
  * 保证类在内存中只有一个对象

* B:如何保证
  * a:控制类的创建,不让其他类来创建泵类的对象,私有化构造方法
  * b:在本类中定义一个本类的对象
  * c:提供公共的访问方式

* C:案例演示
  * 饿汉式,用空间换取时间
  * 懒汉式,用时间换取空间

package com.heima.thread;

public class Demo1_Singleton {
/*
* 饿汉式和懒汉式的区别:
* 1、饿汉式一开始就创建对象浪费空间,但是节省了时间,是用空间换取时间
* 2、懒汉式一开始不创建对象,访问后才判断并创建,浪费了时间,是用时间换取空间
* 3、在多线程访问时,懒汉式有可能创建多个对象
* 4、开发中一般用饿汉式,懒汉式出现在面试中
*/
public static void main(String[] args) {
Singleton2 s1 = Singleton2.getInstance();
Singleton2 s2 = Singleton2.getInstance();
System.out.println(s1 == s2); // true,指向的是同一个对象
}
} class Singleton1 { // 饿汉式
private Singleton1() {}// 私有构造方法,其他类不能访问该构造方法
private static Singleton1 s = new Singleton1(); // 在本类中创建本类对象
public static Singleton1 getInstance() { // 对外提供公共的访问方法
return s;
}
} class Singleton2 { // 懒汉式,单例的延迟加载模式
private Singleton2() {}// 私有构造方法,其他类不能访问该构造方法
private static Singleton2 s; // 声明一个引用,但不创建
public static Singleton2 getInstance() { // 对外提供公共的访问方法
if (s == null) {
// 多线程时可能会创建多个对象
s = new Singleton2(); // 获取实例
}
return s;
}
} class Singleton3 { // 第三种方法
private Singleton3() {}// 私有构造方法,其他类不能访问该构造方法
public static final Singleton3 s = new Singleton3(); // 用final创建对象
}

Singleton

Runtime类

* Runtime类是一个单例类

package com.heima.thread;

import java.io.IOException;

public class Demo2_Runtime {

    public static void main(String[] args) throws IOException {
Runtime r = Runtime.getRuntime(); // Runtime类中私有了构造方法,但内部创建了Runtime对象可以调用方法获取对象
// r.exec("shutdown -s -t 300"); // 300秒后关机
// r.exec("shutdown -a"); // 取消关机
}
}

runtime

Timer类

* Timer类:计时器

package com.heima.thread;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask; public class Demo3_Timer { public static void main(String[] args) throws InterruptedException {
Timer t = new Timer();
// 在指定时间安排指定任务,第一个参数是安排的任务,第二个参数是执行的时间,第三个参数是过多少毫秒后再重复执行
t.schedule(new MyTimerTask(), new Date(120, 3, 12, 9, 3, 30), 3000);
// 年-1900,月-1,日,时-1,分-1,秒-1
while (true) {
Thread.sleep(1000);
System.out.println(new Date());
}
}
} class MyTimerTask extends TimerTask { // 继承TimerTask
@Override
public void run() { // 重写 run()方法
System.out.println("起床背英语");
} }

TimerTask

两个线程间的通信

* A:什么时候需要通信
  * 多个线程并发执行时,在默认情况下CPU是随机切换线程的
  * 如果我们希望他们有规律的执行,就可以使用通信,例如每个线程执行一次打印

* B:怎么通信
  * 如果希望线程等待,就调用 锁对象的 wait()方法
  * 如果希望唤醒等待的线程,就调用 notify()
  * 这两个方法必须在同步代码块中国执行,并且使用同步锁对象来调用

package com.heima.thread2;

public class Demo1_Notify {
// 等待唤醒机制,交替打印
public static void main(String[] args) {
Printer p = new Printer(); new Thread () {
public void run() {
while (true) {
try {
Thread.sleep(1);
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程 1 new Thread () {
public void run() {
while (true) {
try {
Thread.sleep(1);
p.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程 2
}
} class Printer {
private int flag = 1; // 定义特征变量 public void print1() throws InterruptedException {
synchronized (this) {
if (flag != 1) {
this.wait(); // 判断条件,使当前线程等待
} System.out.print("z");
System.out.print("w");
System.out.print("b");
System.out.println(); flag = 2; // 将特征变量修改为2
this.notify(); // 随机唤醒单个等待的线程
}
}
public void print2() throws InterruptedException {
synchronized (this) {
if (flag != 2) {
this.wait(); // 判断条件,使当前线程等待
} System.out.print("c");
System.out.print("l");
System.out.print("y");
System.out.println(); flag = 1; // 将特征变量修改为1
this.notify(); // 随机唤醒单个等待的线程
}
}
}

Notifiy

三个或三个以上的线程间通信

* 多个线程通信的问题
  * notify()方法,随机唤醒一个线程
  * notifyAll()方法,唤醒所有线程
  * JDK5之前无法唤醒指定的线程
  * 如果多个线程间通信,需要使用 notifyAll()通知所有线程,并用 while来反复判断条件

package com.heima.thread2;

public class Demo2_NotifyAll {
/*
* 1、在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法
* 2、wait方法和notify方法定义在Object类中的原因是:锁对象可以是任何对象,而Object是所有类的基类,所以这两种方法需要定义在这个类中
* 3、sleep和wait方法的区别:
* a:sleep:必须传入参数,参数就是时间,时间到了,就自动醒来
* wait:可以传参数也可以不传,如果传参数,就是在参数的时间结束后等待,如果不传入,就是立刻等待
* b:sleep:在同步函数或同步代码块中,不释放锁,睡着了也抱着锁睡
* wait:在同步函数或同步代码块中,释放锁
*/
public static void main(String[] args) {
Printer2 p2 = new Printer2(); new Thread() {
public void run() {
while (true) {
try {
p2.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程1 new Thread() {
public void run() {
while (true) {
try {
p2.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程2 new Thread() {
public void run() {
while (true) {
try {
p2.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程3
}
} class Printer2 {
private int flag = 1; // 定义特征变量 public void print1() throws InterruptedException {
synchronized (this) {
while (flag != 1) {
this.wait(); // 判断条件,使当前线程等待
}
System.out.print("z");
System.out.print("w");
System.out.print("b");
System.out.println(); flag = 2; // 将特征变量修改为 2
this.notifyAll(); // 唤醒所有等待的线程
}
} public void print2() throws InterruptedException {
synchronized (this) {
while (flag != 3) {
this.wait(); // 判断条件,使当前线程等待
}
System.out.print("c");
System.out.print("l");
System.out.print("y");
System.out.println(); flag = 1; // 将特征变量修改为 1
this.notifyAll(); // 唤醒所有等待的线程
}
} public void print3() throws InterruptedException {
synchronized (this) {
while (flag != 2) {
this.wait(); // 判断条件,使当前线程等待
}
System.out.print("x");
System.out.print("h");
System.out.print("n");
System.out.println(); flag = 3; // 将特征变量修改为 3
this.notifyAll(); // 唤醒所有等待的线程
}
}
}

NotifiyAll

互斥锁

* A:同步
  * 使用 ReentrantLock类的 lock()方法和 unlock()方法

* B:通信
  * 使用 ReentrantLock类的 newCondition() 方法可以获取 Condition对象
  * 需要等待的时候使用 Condition的 await()方法,唤醒的时候使用 signal()方法
  * 不同的线程使用不同的 Condition,这样就能区分唤醒的时候该找哪个线程了

package com.heima.thread2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; public class Demo3_ReentrantLock { public static void main(String[] args) {
Printer3 p3 = new Printer3(); // 创建对象 new Thread() {
public void run() {
while (true) {
try {
p3.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程 1 new Thread() {
public void run() {
while (true) {
try {
p3.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程 2 new Thread() {
public void run() {
while (true) {
try {
p3.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); // 开启线程 3
}
} class Printer3 {
private ReentrantLock r = new ReentrantLock(); // 创建锁对象
private Condition c1 = r.newCondition(); // 创建监视器
private Condition c2 = r.newCondition();
private Condition c3 = r.newCondition(); private int flag = 1; // 创建特征变量 public void print1() throws InterruptedException {
r.lock(); // 获取锁
if (flag != 1) {
c1.await(); // 判断条件,使线程等待
} System.out.print("z");
System.out.print("w");
System.out.print("b");
System.out.println(); flag = 2;
c2.signal(); // 在当前线程等待前,唤醒指定线程
r.unlock(); // 释放锁
} public void print2() throws InterruptedException {
r.lock(); // 获取锁
if (flag != 3) {
c3.await(); // 判断条件,使线程等待
}
System.out.print("c");
System.out.print("l");
System.out.print("y");
System.out.println(); flag = 1;
c1.signal(); // 在当前线程等待前,唤醒指定线程
r.unlock(); // 释放锁
} public void print3() throws InterruptedException {
r.lock();// 获取锁
if (flag != 2) {
c2.await(); // 判断条件,使线程等待
}
System.out.print("x");
System.out.print("h");
System.out.print("n");
System.out.println(); flag = 3;
c3.signal(); // 在当前线程等待前,唤醒指定线程
r.unlock();// 释放锁
}
}

ReentrantLock

线程组的概述和使用

* A:线程组的概述
  * Java中使用 ThreadGroup 来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制
  * 默认情况下,所有的线程都属于主线程
    * public final ThreadGroup getThreadGroup() :通过线程对象获取它所属于的组
    * public final String getName() :通过线程组对象获取它的组的名字

  * 我们也可以给线程设置分组
    * ThreadGroup(String name) :创建线程组对象并给其赋值命名
    * Thread(ThreadGroup group, Runnable target, String name) :通过 Thread的构造创建线程并添加到指定组中
    * 设置整组的优先级或者守护线程

* B:案例演示
  * 线程组的使用,默认是主线程组

package com.heima.thread2;

public class Demo4_ThreadGroup {

    public static void main(String[] args) {
// demo1();
// demo2();
} public static void demo2() {
ThreadGroup tg = new ThreadGroup("新线程组"); // 创建新的线程组
MyRunnable mr = new MyRunnable(); // 创建Runnable的子类对象 Thread t1 = new Thread(tg, mr, "张三"); // 将线程t1放在线程组tg中
Thread t2 = new Thread(tg, mr, "李四"); // 将线程t2放在线程组tg中 System.out.println(t1.getThreadGroup().getName()); // 获取线程组的名字
System.out.println(t2.getThreadGroup().getName()); tg.setDaemon(true);
} public static void demo1() {
MyRunnable mr = new MyRunnable(); // 创建Runnable的子类
Thread t1 = new Thread(mr, "张三"); // 创建线程对象并命名
Thread t2 = new Thread(mr, "李四"); ThreadGroup tg1 = t1.getThreadGroup(); // 获取该线程的所属的线程组,如果线程已终止,则返回null
ThreadGroup tg2 = t1.getThreadGroup(); System.out.println(tg1.getName()); // 获取线程组的名字,默认是主线程
System.out.println(tg2.getName());
}
} class MyRunnable implements Runnable { @Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
} }

ThreadGroup

线程的五种状态

线程池的概述和使用

* A:线程池概述
  * 程序启动一个新线程的成本是比较高的,涉及到要与操作系统进行交互
  * 而使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池
  * 线程池里的每一个线程代码结束后并不会死亡,而是再次回到线程池中称为空闲状态,等待下一个对象来使用
  * 在JDK5之前,我们必须手动实现自己的线程池,从JDK5开始,Java内置支持线程池

* B:内置线程池的使用概述
  * JDK5新增了一个 Executors工厂类来生产线程池
    * public static ExecutorService newFixedThreadPool(int nThreads) :指定可以存储几条线程的线程池
    * public static ExecutorService newSingleThreadExecutor()
    * 这些方法的返回值是 ExecutorService对象,该对象表示一个线程池,可以执行Runnable子类或者Callable对象代表的程序
      * Future<?> submit(Runnable task) :将线程仿佛线程池中,并执行
      * <T> Future<T> submit(Callable<T> task)

    * 使用步骤:
      * 创建线程池对象
      * 创建 Runnable实例
      * 提交 Runnable实例
      * 关闭线程池

* C:案例演示
  * 提交的是 Runnable

package com.heima.thread2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class Demo5_Executor { public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2); // 创建可存储指定数量的线程的线程池
pool.submit(new MyRunnable()); // 将线程放进池子里并执行
pool.submit(new MyRunnable()); pool.shutdown(); // 关闭线程池
}
}

ThreadPool

package com.heima.thread2;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class Demo6_Callable { public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(2); // 创建可容纳指定线程数的线程池 Future<Integer> f1 = pool.submit(new MyCallable(10)); // 将线程放进池子里并执行
Future<Integer> f2 = pool.submit(new MyCallable(20)); System.out.println(f1.get());
System.out.println(f2.get());
pool.shutdown(); // 关闭线程池
}
} class MyCallable implements Callable<Integer> {
private int num; public MyCallable(int num) {
super();
this.num = num;
} @Override
public Integer call() throws Exception { // 重写 call()方法
int sum = 0;
for (int i = 0; i <= num; i++) {
sum += i;
}
return sum;
} }

Callable

简单工厂模式概述和使用

* A:简单工厂模式概述
  * 又叫静态工厂方法模式,它定义一个具体的工厂类负则创建一些类的实例

* B:优点
  * 客户端不需要再负则对象的创建,从而明确了各个类的职责

* C:缺点
  * 这个静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断地修改工厂类,不利于后期维护

* D:案例演示
  * 动物抽象类 :public abstract Animal{ public abstract void eat(); }
  * 具体狗类 :public class Dog extends Animal{ }
  * 具体猫类 :public class Cat extends Animal{ }
  * 定义一个专门的类来创建对象

package com.heima.factory;

public abstract class Animal {
public abstract void eat();
}

Animal

package com.heima.factory;

public class Cat extends Animal {

    public void eat() {
System.out.println("猫吃鱼");
} }

Cat

package com.heima.factory;

public class Dog extends Animal {

    public void eat() {
System.out.println("狗吃肉");
} }

Dog

package com.heima.factory;

public class AnimalFactory {
/*public static Dog createDog() {
return new Dog();
} public static Cat createCat() {
return new Cat();
}*/ // 上述方法复用性太差
public static Animal createAnimal(String name) { // 多态返回
if ("Dog".equals(name)) {
return new Dog();
} else if ("Cat".equals(name)) {
return new Cat();
} else {
return null;
}
} }

Factory

package com.heima.factory;

public class Test {

    public static void main(String[] args) {
/*Dog d = AnimalFactory.createDog();
System.out.println(d);*/ Dog d = (Dog)AnimalFactory.createAnimal("Dog");
d.eat(); Cat c = (Cat)AnimalFactory.createAnimal("Cat");
c.eat();
}
}

Test

工厂方法模式的概述和使用

* A:工厂方法模式的概述
  * 工厂方法模式中抽象工厂类负则定义出啊关键对象的接口,具体对象的创建工作由继承抽象工作的具体类实现

* B:优点:
  * 客户端不需要再负则对象的创建,从而明确了各个类的职责,
    如果有新的对象增加,只需要增加一个具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性

* C:缺点:
  * 需要额外的编写代码,增加了工作量

* D:案例演示

package com.heima.facMethod;

public abstract class Animal {
public abstract void eat();
}

Animal

package com.heima.facMethod;

public interface Factory {
public Animal createAnimal();
}

Factory

package com.heima.facMethod;

public class Cat extends Animal {

    public void eat() {
System.out.println("猫吃鱼");
} }

Cat

package com.heima.facMethod;

public class Dog extends Animal {

    public void eat() {
System.out.println("狗吃肉");
} }

Dog

package com.heima.facMethod;

public class CatFactory implements Factory {

    public Animal createAnimal() { // 多态
return new Cat();
} }

CatFactory

package com.heima.facMethod;

public class DogFactory implements Factory {

    public Animal createAnimal() { // 多态
return new Dog();
} }

DogFactory

package com.heima.facMethod;

public class Test {

    public static void main(String[] args) {
DogFactory df = new DogFactory();
Dog d = (Dog)df.createAnimal(); // 返回的是 Animal,需要强转
d.eat();
}
}

Test


创建一个窗口并显示

* A:Graphic User Interface(图像交互接口)

* B:布局管理器
  * FlowLayOut(流式布局管理器)
    * 居中排列,新内容从左到右排列
    * Panel默认的布局管理器
  * BorderLayOut(边界布局管理器)
    * 东南西北中
    * Frame默认的布局管理器
  * GridLayOut(网格布局管理器)
    * 选项卡
  * CardLayOut(卡片布局管理器)
    * 选项卡
  * GridBagLayOut(网格包布局管理器)
    * 非规则的矩阵

* C:监听器
  * 窗体监听,鼠标箭头,键盘监听和键盘事件,动作监听

package com.heima.GUI;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;; public class Demo1_Frame { public static void main(String[] args) {
Frame f = new Frame("我的第一个窗口"); // 给框架一个标题 f.setSize(400, 600); // 设置窗体的大小
f.setLocation(400, 100); // 设置窗体出现的位置 f.setIconImage(Toolkit.getDefaultToolkit().createImage("qq.png")); // 设置图标 Button b1 = new Button("1"); // 创建按钮,并为其命名
Button b2 = new Button("2");
f.add(b1); // 将按钮添加到框架上
f.add(b2); f.setLayout(new FlowLayout()); // 设置布局管理器 f.addWindowListener(new WindowAdapter() { // 在框架上添加窗体监听,传入适配器的匿名子类对象
@Override
public void windowClosing(WindowEvent e) { // 重写 Closeing()方法,使得点击退出按钮时可以退出程序
System.exit(0);
}
}); b1.addMouseListener(new MouseAdapter() { // 在按钮上添加鼠标监听
@Override
public void mouseReleased(MouseEvent e) { // 释放鼠标,GUI退出
System.exit(0);
}
}); b1.addKeyListener(new KeyAdapter() { // 在按钮上添加键盘监听
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) { // 如果按空格键,就退出
System.exit(0);
}
}
}); b2.addActionListener(new ActionListener() { // 在按钮上添加动作监听,默认动作是空格和鼠标左键,应用场景,视频播放器的暂停 @Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}); f.setVisible(true); // 设置窗体可见
}
}

GUI

适配器设计模式

* A:什么是适配器
  * 在使用监听器的时候,需要定义一个类实践监听器接口
  * 通常接口中有多个方法,而程序中不一定所有的都用大,但又必须重写,这很繁琐
  * 适配器简化了这些操作,我们定义监听器时只要继承适配器,然后重写需要的方法即可

* B:适配器原理
  * 适配器就是一个类,实现了监听器接口,所有抽象方法都重写了,但是方法全是空的
  * 适配器类需要定义成抽象的,因为创建该类对象,调用空方法是没有意义的
  * 目的就是为了简化程序员的操作,定义监听器时继承适配器,只重写需要的方法就可以了

package com.heima.adaptor;

public class Demo1_Adaptor {

    public static void main(String[] args) {

    }
} class 鲁智深 extends 中间类 {
public void 习武() {
System.out.println("倒把垂杨柳");
System.out.println("拳打镇关西");
System.out.println("大闹野猪林");
}
} abstract class 中间类 implements 和尚 { // 适配器,不想被实例化,声明成抽象,方法都是空的 @Override
public void 打坐() {
} @Override
public void 念经() {
} @Override
public void 撞钟() {
} @Override
public void 习武() {
} } interface 和尚 {
public void 打坐();
public void 念经();
public void 撞钟();
public void 习武();
}

Adaptor

最新文章

  1. 如何使用PullToRefresh
  2. 【.net+jquery】绘制自定义表单(含源码)
  3. (转)Let’s make a DQN 系列
  4. hihocoder 1388 &amp;&amp;2016 ACM/ICPC Asia Regional Beijing Online Periodic Signal
  5. 基于XMPP的即时通信系统的建立(二)— XMPP详解
  6. [转载]linux下mysql 自动备份
  7. 查询SystemFeature的方法
  8. openwrt路由器更换了Flash之后需要修改的源码
  9. 【微服务】之五:轻松搞定SpringCloud微服务-调用远程组件Feign
  10. MVC实用架构设计(三)——EF-Code First(1):Repository,UnitOfWork,DbContext
  11. pre-commit 钩子,代码质量检查:在 vue-cli 3.x 版本中,已经使用尤大改写的yorkie,yorkie实际是fork husky,然后做了一些定制化的改动,使得钩子能从package.json的 &quot;gitHooks&quot;属性中读取
  12. 解决Ubuntu中文显示为乱码
  13. DirectX之顶点法线的计算
  14. 【colaboratory】ModuleNotFoundError: No module named &#39;forward&#39;
  15. DevOps的概念
  16. cmd运行php
  17. DedeCMS实现自定义表单提交后发送指定QQ邮箱的方法
  18. RTT学习之BSP
  19. Chapter11
  20. HDU2846【字典树】

热门文章

  1. 2019 ICPC Asia Taipei-Hsinchu Regional Problem K Length of Bundle Rope (贪心,优先队列)
  2. Proud Merchants HDU - 3466 01背包&amp;&amp;贪心
  3. P类问题,NP,NPC,HPHard,coNP,NPI问题 的简单认识
  4. python了解未知函数的方法
  5. LWIP再探----内存池管理
  6. js &amp; document.designMode
  7. Promise.allSettled &amp; Promise.all &amp; Promise.race &amp; Promise.any All In One
  8. React &amp; Special Props Warning
  9. Mapbox 地图实验室
  10. LeetCode 高效刷题路径