您的位置:首页 > 编程语言 > Java开发

(十一)、Java复习笔记之多线程(2)

2017-11-20 21:12 429 查看

127、单例设计模式

概述

保证类在内存中只有一个对象。

如何保证类在内存中只有一个对象呢?

控制类的创建,不让其他类来创建本类的对象。

在本类中定义一个本类的对象。

提供公共的访问方式。

单例的三种写法:

饿汉式:开发用这种方式。

//恶汉式
class Singleton {
//1,私有构造函数
private Singleton(){}
//2,创建本类对象
private static Singleton s = new Singleton();
//3,对外提供公共的访问方法
public static Singleton getInstance() {
return s;
}
}


懒汉式:面试写这种方式。多线程情况下有可能会创建多个对象。

//懒汉式,单例的延迟加载模式
class Singleton {
//1,私有构造函数
private Singleton(){}
//2,声明一个本类的引用
private static Singleton s;
//3,对外提供公共的访问方法
public static Singleton getInstance() {
if(s == null)
s = new Singleton();
return s;
}
}


第三种格式

class Singleton {
private Singleton() {}
public static final Singleton s = new Singleton();//final是最终的意思,被final修饰的变量不可以被更改
}


128、Runtime类

每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。

Runtime类是一个单例类。

应用程序不能创建自己的 Runtime 类实例。

Runtime r = Runtime.getRuntime();
//r.exec("shutdown -s -t 300"); //300秒后关机
r.exec("shutdown -a");  //取消关机


129、Timer类

计时器。

一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

public class Demo3_Timer {

public static void main(String[] args) throws InterruptedException {
Timer t = new Timer();
//在指定时间安排指定任务
//第一个参数,是安排的任务,第二个参数是执行的时间,第三个参数是过多长时间再重复执行
t.schedule(new MyTimerTask(), new Date(188, 6, 1, 14, 22, 50),3000);

while(true) {
Thread.sleep(1000);
System.out.println(new Date());
}
}
}

class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("起床背英语单词");
}
}


130、两个线程间的通信

什么时候需要通信

多个线程并发执行时, 在默认情况下CPU是随机切换线程的

如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印

怎么通信

如果希望线程等待, 就调用wait()

如果希望唤醒等待的线程, 就调用notify();

这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用

public class Demo1_Notify {

/**
* @param args
* 等待唤醒机制
*/
public static void main(String[] args) {
final Printer p = new Printer();

new Thread() {
public void run() {
while(true) {
try {
p.print1();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}.start();

new Thread() {
public void run() {
while(true) {
try {
p.print2();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}.start();
}

}

//等待唤醒机制
class Printer {
private int flag = 1;
public void print1() throws InterruptedException {
synchronized(this) {
if(flag != 1) {
this.wait(); //当前线程等待。在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法
}
System.out.print("我");
System.out.print("爱");
System.out.print("你");
System.out.print("中");
System.out.print("国");
System.out.print("\r\n");
flag = 2;
this.notify();  //随机唤醒单个等待的线程
}
}

public void print2() throws InterruptedException {
synchronized(this) {
if(flag != 2) {
this.wait();
}
System.out.print("石");
System.out.print("头");
System.out.print("真");
System.out.print("棒");
System.out.print("\r\n");
flag = 1;
this.notify();
}
}
}


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

notify()方法是随机唤醒一个线程

notifyAll()方法是唤醒所有线程

如果多个线程之间通信, 需要使用notifyAll()通知所有线程, 用while来反复判断条件

class Printer2 {
private int flag = 1;
public void print1() throws InterruptedException {
synchronized(this) {
while(flag != 1) {
this.wait(); //在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法
}
System.out.print("我");
System.out.print("爱");
System.out.print("你");
System.out.print("中");
System.out.print("国");
System.out.print("\r\n");
flag = 2;
this.notifyAll();
}
}

public void print2() throws InterruptedException {
synchronized(this) {
while(flag != 2) {
this.wait(); //线程2在此等待
}
System.out.print("传");
System.out.print("智");
System.out.print("播");
System.out.print("客");
System.out.print("\r\n");
flag = 3;
this.notifyAll();
}
}

public void print3() throws InterruptedException {
synchronized(this) {
while(flag != 3) {
this.wait(); //线程3在此等待,if语句是在哪里等待,就在哪里起来
//while循环是循环判断,每次都会判断标记
}
System.out.print("椰");
System.out.print("子");
System.out.print("\r\n");
flag = 1;
this.notifyAll();
}
}
}


132、为什么wait()方法和notify()方法定义在Object类中?

因为锁对象可以是任意对象,Object是所有的类的基类,所以wait方法和notify方法需要定义在Object这个类中。

在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法

133、sleep()方法和wait()方法的区别

sleep()是线程类(Thread)的方法,wait()是Object 类的方法。

sleep()方法必须传入参数,参数就是时间,时间到了自动醒来。

wait()方法可以传入参数也可以不传入参数,传入参数就是在参数的时间结束后等待,不传入参数就是直接等待。需要被唤醒(notify)才能进入运行状态。

sleep()方法在同步方法或同步代码块中,不释放锁(一直等待,不执行其他线程)

wait()方法在同步方法或者同步代码块中,释放锁

134、互斥锁

同步

使用ReentrantLock 类的lock()和unlock()方法进行同步

通信

使用ReentrantLock 类的newCondition()方法可以获取Condition 对象

需要等待的时候使用Condition 的await()方法, 唤醒的时候用signal()方法

不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了

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) { //if语句是在哪里等待,就在哪里起来
c1.await();
}
System.out.print("我");
System.out.print("爱");
System.out.print("你");
System.out.print("中");
System.out.print("国");
System.out.print("\r\n");
flag = 2;
c2.signal();
r.unlock(); //释放锁
}

public void print2() throws InterruptedException {
r.lock();
if(flag != 2) {
c2.await();
}
System.out.print("石");
System.out.print("头");
System.out.print("真");
System.out.print("棒");
System.out.print("\r\n");
flag = 3;
c3.signal();
r.unlock();
}

public void print3() throws InterruptedException {
r.lock();
if(flag != 3) {
c3.await();
}
System.out.print("椰");
System.out.print("子");
System.out.print("\r\n");
flag = 1;
c1.signal();
r.unlock();
}
}


135、线程组

概述

Java中使用ThreadGroup 来表示线程组,它可以对一批线程进行分类管理,Java允许程序直接对线程组进行控制。

默认情况下,所有的线程都属于主线程组。

实例

public static void main(String[] args) {
ThreadGroup tg = new ThreadGroup("我是一个新的线程组");  //创建新的线程组
MyRunnable mr = new MyRunnable();   //创建Runnable的子类对象

Thread t1 = new Thread(tg, mr, "张三");   //将线程t1放在组中
Thread t2 = new Thread(tg, mr, "李四");   //将线程t2放在组中

System.out.println(t1.getThreadGroup().getName());  //获取组名
System.out.println(t2.getThreadGroup().getName());

tg.setDaemon(true);
}

class MyRunnable implements Runnable {

@Override
public void run() {
for(int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
}


136、线程的五种状态

新建,就绪,运行,阻塞,死亡



137、线程池(Executors)

概述

程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池。线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用。

方法

public static ExecutorService newFixedThreadPool(int nThreads)

public static ExecutorService newSingleThreadExecutor()

这些方法的返回值是ExecutorService 对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程。它提供了如下方法

Future< ? > submit(Runnable task)

Future submit(Callable task)

使用步骤:

创建线程池对象

创建Runnable实例

提交Runnable实例

关闭线程池

public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池
pool.submit(new MyRunnable());  //将线程放进池子里并执行
pool.submit(new MyRunnable());

pool.shutdown();//关闭线程池
}


138、多线程程序实现的方式3(了解)

好处:

可以有返回值

可以抛出异常

弊端:

代码比较复杂,所以一般不用

实例

public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池
Future<Integer> f1 = pool.submit(new MyCallable(100));  //将线程放进池子里并执行
Future<Integer> f2 = pool.submit(new MyCallable(50));

System.out.println(f1.get());
System.out.println(f2.get());

pool.shutdown(); //关闭线程池
}

class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for(int i = 1; i <= num; i++) {
sum += i;
}
return sum;
}
}


139、简单工厂模式

概述

又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例

优点

客户端不需要在负责对象的创建,从而明确了各个类的职责

缺点

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

实例

开始,在测试类中每个具体的内容自己创建对象,但是,创建对象的工作如果比较麻烦,就需要有人专门做这个事情,所以就使用了一个专门的类来创建对象。

//动物抽象类
public abstract Animal {
public abstract void eat();
}

//具体狗类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}

//具体猫类
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}

//工厂类
public class AnimalFactory {
public static Animal createAnimal(String name) {
if("dog".equals(name)) {
return new Dog();
}else if("cat".equals(name)) {
return new Cat();
}else {
return null;
}
}
}

//测试
public static void main(String[] args) {
Dog d = (Dog) AnimalFactory.createAnimal("dog");
d.eat();

Cat c = (Cat) AnimalFactory.createAnimal("cat");
c.eat();
}


140、工厂方法模式

概述

工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。

优点

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

缺点

需要额外的编写代码,增加了工作量

实例

开始,在测试类中每个具体的内容自己创建对象,但是,创建对象的工作如果比较麻烦,就需要有人专门做这个事情,所以就使用了一个专门的类来创建对象。发现每次修改代码太麻烦,用工厂方法改进,针对每一个具体的实现提供一个具体工厂。

//动物抽象类、具体狗类、具体猫类

//抽象工厂类
public interface Factory {
public Animal createAnimal();
}

//狗工厂
public class DogFactory implements Factory {
@Override
public Animal createAnimal() {
return new Dog();
}
}

//猫工厂
public class CatFactory implements Factory {
@Override
public Animal createAnimal() {
return new Cat();
}
}

//测试
public static void main(String[] args) {
DogFactory df = new DogFactory();
Dog d = (Dog) df.createAnimal();
d.eat();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息