线程间通信

本文详细介绍了Java中四种线程间通信方式:1) 共享变量,通过同步块访问共享对象数据;2) wait/notify机制,利用Object类中的wait(), notify()进行通信;3) Lock和Condition机制,提供更灵活的同步控制;4) 管道,用于线程间的双向数据传递。文中通过示例代码解析了每种通信方式的工作原理和使用场景。" 102452125,6430503,Handsontable核心方法与操作指南,"['前端开发', 'JavaScript', '表格库', '数据管理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程间的通信方式主要有如下4种方式:
1)共享变量;
2)wait, notify机制;
3)Lock, Condition机制;
4)管道
下面将逐一讲解这4中线程间通信方式。

1. 共享变量

线程之间通过共享一个对象,在同步块中访问该对象中数据来实现通信。
下面是一个例子,创建了两个线程thread1和thread2,创建了Runnable实现类对象task,thread1和thread2共享task对象,在synchronized同步块中访问count数据,实现两个线程间的通信。

public class Main5 implements Runnable {

    public Integer count=0;

    public void run(){
        int temp;
        synchronized(this){
            count++;
            temp=count;
        }
        System.out.println(Thread.currentThread().getName()+" count: "+temp);
    }

    public static void main(String args[]){
        Main5 task=new Main5();
        Thread thread1=new Thread(task,"thread1");
        Thread thread2=new Thread(task,"thread2");
        thread1.start();
        thread2.start();
    }
}

2. wait/notify机制

wait(), notify(), notifyAll(), 这三个方法定义于Object类中,会被所有的类所继承。同时这三个方法都是final修饰的方法,在子类中不能对这三个方法进行重写。

wait方法使得当前线程必须要等待,直到其他线程线程调用notify方法或者notifyAll方法。
当调用wait方法将会释放掉当前持有的锁,等待其他线程调用notify或者notifyAll方法来通知,方能重新获得锁从而恢复运行。
在调用wait方法确保拥有锁,所以通常在synchronized方法或者synchronized同步块中调用wait方法。
使得线程线程暂停的另外一个方法:java.lang.Thread.sleep,它会导致线程暂停睡眠特定的时间,但是在睡眠的过程中不会释放掉所拥有的锁。而wait方法将会释放所拥有的锁。

notify方法将会唤醒一个等待当前对象锁的线程。
如果多个线程在等待,那么其中的一个将会被唤醒。被唤醒的线程是任意选择的,和自行实现有关。
被唤醒的线程不会被立即执行,而是等到调用notify方法的线程让出锁后。
被唤醒的线程将会以平常的方式与其他可能需要该对象锁的线程进行竞争,换句话说,被唤醒的线程并没有任何的特权或者优势去称为该锁的下一个持有者。
在线程调用该方法之前,必须拥有该对象的锁,而获取锁的途径有以下三种:
1)通过执行该对象的synchronized方法;
2)通过执行该对象的额synchronized代码块;
3)对于Class类型对象,通过执行synchronized static 方法;

示例程序如下,该程序的作用是通过wait/notify通信方式保证程序先进行加法操作,在进行减法操作。

//操作数
public class Acount {

    private int a;

    public Acount(int aa){
        a=aa;
    }

    public void addA(){
        a++;
    }

    public void decA(){
        a--;
    }

    public Integer getA(){
        return a;
    }

}

//加法线程
public class AddThread extends Thread{

    private Acount acount;

    public AddThread(Acount acount,String name){
        super(name);
        this.acount=acount;
    }
    public void run(){
        synchronized(acount){
            acount.addA();
            acount.notify();
            try{
                Thread.sleep(1000);
            }catch(Exception e){
                e.printStackTrace();
            }     //检测在执行notify方法后不会立即释放锁,而是等到执行完run方法体
            System.out.println(getName()+" : "+acount.getA());
        }
    }
}

//减法线程
public class DecThread extends Thread{
    private Acount acount;
    public DecThread(Acount acount,String name){
        super(name);
        this.acount=acount;
    }
    public void run(){
        synchronized(acount){
            System.out.println(getName()+" : "+acount.getA());
            try{
                acount.wait();
            }catch(Exception e){
                e.printStackTrace();
            }
            acount.decA();
            System.out.println(getName()+" : "+acount.getA());
        }
    }
}

//主程序
public class Main7 {
    public static void main(String args[]){
        Acount acount=new Acount(100);
        AddThread addThread=new AddThread(acount,"add_thread");
        DecThread decThread=new DecThread(acount,"dec_thread");
        decThread.start();   
        try{
            Thread.sleep(1000);  //确保减法线程先执行
        }catch(Exception e){
            e.printStackTrace();
        }
        addThread.start();
    }
}

3. Lock/Condition机制

如果程序不采用synchronized关键字进行同步控制,而是采用Lock对象进行同步控制,那么程序就不能使用隐式的同步监控对象,因而也就不能使用wait(), notify(), notifyAll方法来协调线程的运行。
当使用Lock对象进行同步时,Java提供Condition类来协调线程的运行。

对前面的wait/notify通信机制的示例程序改为Lock/Condition通信机制,修改后的程序如下:


//操作数
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

public class Acount {

    private int a;
    private Lock lock;
    private Condition con;

    public Acount(int aa){
        a=aa;
        lock=new ReentrantLock();
        con=lock.newCondition();
    }

    public void addA(){
        lock.lock();
        a++;
        con.signal();

        System.out.println(Thread.currentThread().getName()+" : "+a);
        lock.unlock();
    }

    public void decA(){
        lock.lock();
        System.out.println(Thread.currentThread().getName()+" : "+a);

        try{
            con.await();
        }catch(Exception e){
            e.printStackTrace();
        }

        a--;
        lock.unlock();
        System.out.println(Thread.currentThread().getName()+" : "+a);
    }

}

//减法线程
public class DecThread extends Thread{
    private Acount acount;
    public DecThread(Acount acount,String name){
        super(name);
        this.acount=acount;
    }
    public void run(){
        acount.decA();
    }
}

//加法操作线程
public class AddThread extends Thread{

    private Acount acount;

    public AddThread(Acount acount,String name){
        super(name);
        this.acount=acount;
    }
    public void run(){
        acount.addA();
    }
}

//主程序
public class Main7 {
    public static void main(String args[]){
        Acount acount=new Acount(100);
        AddThread addThread=new AddThread(acount,"add_thread");
        DecThread decThread=new DecThread(acount,"dec_thread");
        decThread.start();   
        try{
            Thread.sleep(1000);  //确保减法线程先执行
        }catch(Exception e){
            e.printStackTrace();
        }
        addThread.start();
    }
}

4. 管道

管道流是Java线程常用的通信方式,该通信机制的主要流程如下:
1)创建管道输出流PipedOutputStream pos和管道输入流PipedInputStream pis;
2)将管道输出流连接到管道输入流;
2)将管道输出流赋给写信息的线程,将管道输入流赋给接收信息的线程;

示例程序如下:

//写线程
import java.io.PipedOutputStream;

public class OutIO extends Thread{
    private PipedOutputStream pos;

    public OutIO(PipedOutputStream pos){
        this.pos=pos;
    }

    public void run(){
        String s="hello,world";
        try{
            pos.write(s.getBytes());
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("write the words: "+s);
    }
}

//读线程
import java.io.PipedInputStream;
public class InIo extends Thread{
    private PipedInputStream pis;

    public InIo(PipedInputStream pis){
        this.pis=pis;
    }

    public void run(){
        byte[] bytes=new byte[20];
        try{
            pis.read(bytes,0,20);
            String temp=new String(bytes);
            temp=temp.trim();
            System.out.println("get the words: "+temp);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

//主程序
import java.io.PipedOutputStream;
import java.io.PipedInputStream;
public class Main8 {
    public static void main(String args[]){
        PipedOutputStream pos=new PipedOutputStream();
        PipedInputStream pis=new PipedInputStream();

        try{
            pos.connect(pis);
        }catch(Exception e){
            e.printStackTrace();
        }

        OutIO outIO=new OutIO(pos);
        InIo inIO=new InIo(pis);
        outIO.start();
        inIO.start();
    }
}

管道流只能在两个线程之间进行传递数据。

参考博客:
http://blog.youkuaiyun.com/ls5718/article/details/51878770

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值