IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java多线程_线程间通信 -> 正文阅读

[Java知识库]Java多线程_线程间通信

等待通知机制

等待通知机制的实现

wait()作用就是使当前执行代码进程进行等待,只能在同步方法和同步块中调用。当前线程释放锁,在wait()返回前,线程及其其它线程竞争重新获得锁。
notify()方法只能在同步方法和同步块中调用。
在这里插入图片描述
在这里插入图片描述

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        try {
            Object lock = new Object();
            ThreadA aThread = new ThreadA(lock);
            ThreadB bThread = new ThreadB(lock);
            aThread.start();
            Thread.sleep(50);
            bThread.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class ThreadA extends Thread {
    private Object lock;
    public ThreadA(Object lock) {
        this.lock = lock;
    }
    @Override
    public void run() {
        super.run();
        try {
            synchronized (lock) {
                if (MyList.size() != 5) {
                    System.out.println("wait begin " + System.currentTimeMillis());
                    lock.wait();
                    System.out.println("wait end " + System.currentTimeMillis());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class ThreadB extends Thread {
    private Object lock;
    public ThreadB(Object lock) {
        this.lock = lock;
    }
    @Override
    public void run() {
        super.run();
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                MyList.add();
                if (MyList.size() == 5) {
                    lock.notify();
                    System.out.println("notify sent!");
                }
                System.out.println("add " + (i + 1));
            }
        }
    }
}
package multiply.com.test;
import java.util.ArrayList;
import java.util.List;
public class MyList {
    private static List<String> list = new ArrayList<>();
    public static void add() {
        list.add("anyString");
    }
    public static int size() {
        return list.size();
    }
}

wait begin 1635219350053
add 1
add 2
add 3
add 4
notify sent!
add 5
add 6
add 7
add 8
add 9
add 10
wait end 1635219350104
在这里插入图片描述

当interrupt方法遇到了wait方法

在这里插入图片描述

方法wait(long)的使用

在这里插入图片描述

通知过早

如果通知过早,会打乱程序正常运行的逻辑。
在这里插入图片描述

package multiply.com.test;
public class MyRun1 {
    private String lock = new String("");
    private boolean isFirstRunB = false;
    private Runnable runnableA = new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    while (!isFirstRunB) {
                        System.out.println("begin wait");
                        lock.wait();
                        System.out.println("  end wait");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    private Runnable runnableB = new Runnable() {
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("notify begin");
                lock.notify();
                System.out.println("notify   end");
                isFirstRunB = true;
            }
        }
    };
    public static void main(String[] args) throws InterruptedException {
        MyRun1 run = new MyRun1();
        Thread a = new Thread(run.runnableA);
        Thread b = new Thread(run.runnableB);
        a.start();
        b.start();
    }
}

notify begin
notify end

生产者和消费者模式实现

多生产者与多消费者:操作值-假死

package multiply.com.test;
public class Run {
    public static void main(String[] args) throws InterruptedException {
        String lock = "";
        int pLen = 2;
        int cLen = 2;
        P p = new P(lock);
        C c = new C(lock);
        ThreadP[] pThread = new ThreadP[pLen];
        ThreadCu[] cThread = new ThreadCu[cLen];
        for (int i = 0; i < pLen; i++) {
            pThread[i] = new ThreadP(p);
            pThread[i].setName("Provider " + (i + 1));
            pThread[i].start();
        }
        for (int i = 0; i < cLen; i++) {
            cThread[i] = new ThreadCu(c);
            cThread[i].setName("consumer " + (i + 1));
            cThread[i].start();
        }
        Thread.sleep(5000);
        Thread[] threads = new Thread[Thread.currentThread().getThreadGroup().activeCount()];
        Thread.currentThread().getThreadGroup().enumerate(threads);
        for (int i = 0; i < threads.length; i++) {
            System.out.println(threads[i].getName() + " " + threads[i].getState());
        }
    }
}
package multiply.com.test;
public class ThreadCu extends Thread {
    private C c;
    public ThreadCu(C c) {
        this.c = c;
    }
    @Override
    public void run() {
        super.run();
        while (true) {
            c.getValue();
        }
    }
}
package multiply.com.test;
public class ThreadP extends Thread {
    private P p;
    public ThreadP(P p) {
        this.p = p;
    }
    @Override
    public void run() {
        super.run();
        while (true) {
            p.setValue();
        }
    }
}
package multiply.com.test;
public class C {
    private String lock;
    public C(String lock) {
        this.lock = lock;
    }
    public void getValue() {
        try {
            synchronized (lock) {
                Thread.sleep(100);
                while ("".equals(ValueObject.value)) {
                    System.out.println("consumer " + Thread.currentThread().getName() + " waiting ");
                    lock.wait();
                }
                System.out.println("consumer " + Thread.currentThread().getName() + " runnable ");
                System.out.println("get value = " + ValueObject.value);
                ValueObject.value = "";
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class P {
    private String lock;
    public P(String lock) {
        this.lock = lock;
    }
    public void setValue() {
        try {
            synchronized (lock) {
                Thread.sleep(100);
                while (!ValueObject.value.equals("")) {
                    System.out.println("provider " + Thread.currentThread().getName() + " waiting ");
                    lock.wait();
                }
                System.out.println("provider " + Thread.currentThread().getName() + " runnable ");
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                System.out.println("set value = " + value);
                ValueObject.value = value;
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
多生产与多消费:操作数栈

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        P[] p = new P[5];
        C[] c = new C[6];
        ThreadP[] pThread = new ThreadP[5];
        ThreadC[] cThread = new ThreadC[6];
        for (int i = 0; i < 5; i++) {
            p[i] = new P(myStack);
            pThread[i] = new ThreadP(p[i]);
            pThread[i].setName("p thread " + i);
            pThread[i].start();
        }
        for (int i = 0; i < 6; i++) {
            c[i] = new C(myStack);
            cThread[i] = new ThreadC(c[i]);
            cThread[i].setName("c thread " + i);
            cThread[i].start();
        }
    }
}
package multiply.com.test;
public class C {
    private MyStack myStack;
    public C(MyStack myStack) {
        this.myStack = myStack;
    }
    public void popService() {
        System.out.println("pop = " + myStack.pop());
    }
}
package multiply.com.test;
public class P {
    private MyStack myStack;
    public P(MyStack myStack) {
        this.myStack = myStack;
    }
    public void pushService() {
        myStack.push();
    }
}
package multiply.com.test;
public class ThreadC extends Thread {
    private C c;
    public ThreadC(C c) {
        this.c = c;
    }
    @Override
    public void run() {
        super.run();
        while (true) {
            c.popService();
        }
    }
}
package multiply.com.test;
public class ThreadP extends Thread {
    private P p;
    public ThreadP(P p) {
        this.p = p;
    }
    @Override
    public void run() {
        super.run();
        while (true) {
            p.pushService();
        }
    }
}
package multiply.com.test;

import java.util.ArrayList;
import java.util.List;
public class MyStack {
    private List<String> list = new ArrayList<>();
    synchronized public void push() {
        try {
            while (list.size() == 1) {
                this.wait();
            }
            list.add("anyString = " + Math.random());
            this.notifyAll();
            System.out.println("push = " + list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public String pop() {
        String returnValue = "";
        try {
            while (list.size() == 0) {
                System.out.println("pop thread " + Thread.currentThread().getName() + " process is waiting");
                this.wait();
            }
            returnValue = "" + list.get(0);
            list.remove(0);
            this.notifyAll();
            System.out.println("pop = " + list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return returnValue;
    }
}

在这里插入图片描述

通过管道进行线程间通信:字节流

在这里插入图片描述
第一种是创建字节流。第二种是创建字符流。

package multiply.com.test;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Run {
    public static void main(String[] args) throws IOException, InterruptedException {
        WriteData writeData = new WriteData();
        ReadData readData = new ReadData();
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        out.connect(in);
        ReadThread readThread = new ReadThread(readData, in);
        WriteThread writeThread = new WriteThread(writeData, out);
        readThread.start();
        Thread.sleep(2000);
        writeThread.start();
    }
}
package multiply.com.test;
import java.io.PipedInputStream;
public class ReadThread extends Thread {
    private ReadData read;
    private PipedInputStream in;
    public ReadThread(ReadData read, PipedInputStream in) {
        this.read = read;
        this.in = in;
    }
    @Override
    public void run() {
        super.run();
        read.readMethod(in);
    }
}
package multiply.com.test;
import java.io.PipedOutputStream;
public class WriteThread extends Thread {
    private WriteData writeData;
    private PipedOutputStream out;
    public WriteThread(WriteData writeData, PipedOutputStream out) {
        this.writeData = writeData;
        this.out = out;
    }
    @Override
    public void run() {
        super.run();
        writeData.writeMethod(out);
    }
}
package multiply.com.test;
import java.io.IOException;
import java.io.PipedInputStream;
public class ReadData {
    public void readMethod(PipedInputStream in) {
        try {
            System.out.println("read : ");
            byte[] bytes = new byte[20];
            int length = in.read(bytes);
            while (length != -1) {
                String newData = new String(bytes, 0, length);
                System.out.print(newData);
                length = in.read(bytes);
            }
            System.out.println();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
import java.io.IOException;
import java.io.PipedOutputStream;
public class WriteData {
    public void writeMethod(PipedOutputStream out) {
        try {
            System.out.println("write : ");
            for (int i = 0; i < 300; i++) {
                String outData = "" + (i + 1);
                out.write(outData.getBytes());
                System.out.print(outData);
            }
            System.out.println();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

方法join的使用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package multiply.com.test;
public class Test {
    public static void main(String[] args) {
        try {
            MyThread thread = new MyThread();
            thread.start();
            thread.join(2000);
            System.out.println("End timer = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("begin timmer = " + System.currentTimeMillis());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

begin timmer = 1635257078799
End timer = 1635257080818
在这里插入图片描述

类ThreadLocal的使用

在这里插入图片描述

验证线程变量的私有性

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("Main process value = " + Tools.t1.get());
                Thread.sleep(100);
            }
            Thread.sleep(5000);
            ThreadA a = new ThreadA();
            a.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
import java.util.Date;
public class ThreadLocalExt extends ThreadLocal<Long> {
    @Override
    protected Long initialValue() {
        return System.currentTimeMillis();
    }
}
package multiply.com.test;
public class ThreadA extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("ThreadA process value = " + Tools.t1.get());
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class Tools {
    public static ThreadLocalExt t1 = new ThreadLocalExt();
}

在这里插入图片描述
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
Main process value = 1635257609963
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
ThreadA process value = 1635257615968
在这里插入图片描述

package multiply.com.test;
public class Run {
    public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("Main process value = " + Tools.t1.get());
                Thread.sleep(102);

            }
            Thread.sleep(5000);
            ThreadA a = new ThreadA();
            a.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class Tools {
    public static InheritableThreadLocalExt t1 = new InheritableThreadLocalExt();
}
package multiply.com.test;
public class ThreadA extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println("ThreadA process value = " + Tools.t1.get());
                Thread.sleep(101);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package multiply.com.test;
public class InheritableThreadLocalExt extends InheritableThreadLocal<Long> {
    @Override
    protected Long initialValue() {
        return System.currentTimeMillis();
    }
}

Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
Main process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
ThreadA process value = 1635258018157
在这里插入图片描述

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章           查看所有文章
加:2021-10-27 12:42:26  更:2021-10-27 12:44:39 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 0:15:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码