《Java多线程编程核心技术_高洪岩 著》读后整理03

2017-05-18  本文已影响0人  Jthan

第3章 线程间通信

线程是操作系统中独立的个体,但这些个体如果不经过特殊的处理就不能成为一个整体。线程间的通信就是成为整体的必用方案之一,可以说,使线程间进行通信后,系统之间的交互性会更强大,在大大提高CPU利用率的同时还会使程序员对各线程任务在处理的过程中进行有效的把控与监督。


wait / notify
1)执行完同步代码块就会释放对象的锁。
2)在执行同步代码块的过程中,遇到异常而导致线程终止,锁也会被释放。
3)在执行同步代码块的过程中,执行了锁所属对象的wait()方法,这个线程会释放对象锁,而此线程对象会进入线程等待池中,等待被唤醒。
while (list.size() == 1){
    this.wait();//待下次获得锁时接着执行while中的代码
}

通过管道进行线程间通信:字节流/字符流
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedReader;

//读字节流/字符流
public class ReadData {

    public void readMethod(PipedInputStream inputStream) {
        try {
            System.out.println("read :");
            byte[] byteArray = new byte[20];
            int readLength = inputStream.read(byteArray);
            while (readLength != -1) {
                String newData = new String(byteArray, 0, readLength);
                System.out.println(newData);
                readLength = inputStream.read(byteArray);
            }
            System.out.println();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readCharIO(PipedReader reader) {
        try {
            System.out.println("read :");
            char[] charArray = new char[20];
            int readLength = reader.read(charArray);
            while (readLength != -1) {
                String newData = new String(charArray, 0, readLength);
                System.out.println(newData);
                readLength = reader.read(charArray);
            }
            System.out.println();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

import java.io.IOException;
import java.io.PipedOutputStream;
import java.io.PipedWriter;

//写字节流/字符流
public class WriteData {

    public void writeMethod(PipedOutputStream outputStream) {
        try {
            System.out.println("write :");
            for (int i = 0; i < 300; i++) {
                String outData = "" + (i + 1);
                outputStream.write(outData.getBytes());
                System.out.println(outData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeCharIO(PipedWriter writer) {
        try {
            System.out.println("write :");
            for (int i = 0; i < 300; i++) {
                String outData = "" + (i + 1);
                writer.write(outData);
                System.out.println(outData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

import java.io.*;

//测试
public class Run_W_R {
    public static void main(String[] args) {
        try {
            WriteData writeData = new WriteData();
            ReadData readData = new ReadData();

            PipedInputStream inputStream = new PipedInputStream();
            PipedWriter writer = new PipedWriter();
            PipedOutputStream outputStream = new PipedOutputStream();
            PipedReader reader = new PipedReader();

            //inputStream.connect(outputStream);// 连接,这两行写其中一个就行
            outputStream.connect(inputStream);
            writer.connect(reader);

            ThreadWrite threadWrite = new ThreadWrite(writeData, outputStream, writer);
            threadWrite.start();

            Thread.sleep(2000);

            ThreadRead threadRead = new ThreadRead(readData, inputStream, reader);
            threadRead.start();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

join

在很多情况下, 主线程创建并启动子线程,如果子线程中要进行大量的耗时运算,主线程往往将早于子线程结束之前结束。这时, 如果主线程想等待子线程执行完成之后再结束,比如子线程处理一个灵气,主线程要取得这个子线程中的值,就要用到join()方法了。方法join()的作用是等待线程对象销毁。

主线程与子线程是相对而言的,并非指main线程,如:

// 主线程

public class Father extends Thread {
public void run() {
Son s = new Son();
s.start();
s.join();
...
}
}
// 子线程
public class Son extends Thread {
public void run() {
...
}
}

说明:

上面的有两个类Father(主线程类)和Son(子线程类)。因为Son是在Father中创建并启动的,所以,Father是主线程类,Son是子线程类。
在Father主线程中,通过new Son()新建“子线程s”。接着通过s.start()启动“子线程s”,并且调用s.join()。在调用s.join()之后,Father主线程会一直等待,直到“子线程s”运行完毕;在“子线程s”运行完毕之后,Father主线程才能接着运行。 这也就是我们所说的“join()的作用,是让主线程会等待子线程结束之后才能继续运行”!

    /**
     * java version "1.7.0_79"
     * Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
     * Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
     */
    public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);//所以join()会让出CPU
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
threadTest.join(2000);//只等2秒

ThreadLocal / InheritableThreadLocal

多个类间数据共享,例Controller中想用其它类中某个方法的结果,但又不能调用等。

变量wfhgr共享可以使用publi static变量的形式,所有的线程都使用同一个public static变量。如果想实现每一个线程都有自己的共享变量该如何解决呢?JDK中提供的类ThreadLocal正是为了解决这样的问题。

ThreadLocal主要解决的就是每个线程绑定自己的值,可以将ThreadLocal类比喻成全局存放数据的盒子,盒子中可以存储每个线程的私有数据。

也就是不同线程拥有自己的值。

public class Run {
    public static ThreadLocal tl = new ThreadLocal();
    
    publi static void main(String[] args) {
        if (tl.get() == null) {
            System.out.println("从未放过值");
            tl.set("我的值");//赋值
        }
        System.out.println(tl.get());//取值
    }
}
public class ThreadLocalExt extends ThreadLocal {
    @Override
    protected Object initialValue() {
        //return null;
        return "default value";
    }
}
class Tools {
    public static InheritableThreadLocal tl = new InheritableThreadLocal();
}

class Father extends Thread {

    @Override
    public void run() {
        Tools.tl.set("Father thread");
        Son son = new Son();
        son.start();
        try {
            son.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("F :" + Tools.tl.get());
    }
}

//子线程中没有赋值时可以取到父线程中存入的值
//子线程中写入自己的值时取到的就是自己的值
class Son extends Thread {

    @Override
    public void run() {
        //Tools.tl.set("Son thread");
        System.out.println("S :" + Tools.tl.get());
    }
}

class FS {
    public static void main(String[] args) throws InterruptedException {
        Father father = new Father();
        father.start();
        father.join();
        System.out.println("end");
    }
}

但在使用InheritableThreadLocal类需要注意一点的是, 如果子线程在取得值的同时, 主线程将InheritableThreadLocal中的值进行更改,那么子线程取到的值还是旧值。

上一篇 下一篇

猜你喜欢

热点阅读