多线程下为什么用while代替if判断

虚假唤醒

线程也可以唤醒,而不会被通知,中断或超时,即所谓的虚假唤醒 。 虽然这在实践中很少会发生,但应用程序必须通过测试应该使线程被唤醒的条件来防范,并且如果条件不满足则继续等待。 换句话说,等待应该总是出现在循环中,就像这样:
synchronized (obj) {
while ()
obj.wait(timeout);
… // Perform action appropriate to condition
}

这是jdk1.8文档里面的内容,虚假唤醒通俗来说就是当一个条件满足时可以唤醒多个线程,但有的被唤醒的线程是没用的

用while代替if

请看下面的代码,不复杂,就是生产者消费者问题,我们要证明的是:

就是用if判断的话,唤醒后线程会从wait之后的代码开始运行,但是不会重新判断if条件,直接继续运行if代码块之后的代码,而如果使用while的话,也会从wait之后的代码运行,但是唤醒后会重新判断循环条件,如果不成立再执行while代码块之后的代码块,成立的话继续wait

这段话

public class consumerAndProductor {
    public static void main(String[] args) {
        clerk c = new clerk();
        consumer t1 = new consumer(c);
        producer t2 = new producer(c);
        t1.setName("消费者");
        t2.setName("生产者");
        t1.start();
        t2.start();
    }
}
class clerk{

    private int count = 50;

    public synchronized void cons() throws InterruptedException {

            while(count == 0){
                this.wait();
                System.out.println(this.getClass()+"-----------");
            }
            System.out.println(Thread.currentThread().getName() + ":消费了" + --count);
            notify();
    }

    public synchronized void pro() throws InterruptedException {
        while(count != 0){
            this.wait();
            System.out.println(this.getClass()+"+++++++++");
        }
        System.out.println(Thread.currentThread().getName() + ":生产了" + ++count);
        notify();
    }

}




class consumer extends Thread{

    private clerk clerk;

    public consumer(syn.clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0;i < 100 ;i++){

            try {
                clerk.cons();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}






class producer extends Thread{

    private clerk clerk;

    public producer(syn.clerk clerk) {
        this.clerk = clerk;
    }


    @Override
    public void run() {
        for (int i = 0;i < 100 ;i++){

            try {
                clerk.pro();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

截取一段运行代码:

消费者:消费了45
消费者:消费了44
消费者:消费了43
消费者:消费了42
class syn.clerk+++++++++
消费者:消费了41
class syn.clerk+++++++++
消费者:消费了40

结论

一个被唤醒的线程就处于就绪状态了,就可以等待被cpu调度了,但是在if语句中,线程被唤醒就从被唤醒的地方执行,不会再次判断,而在while循环中,从被唤醒的地方开始执行代码,至始至终都在while循环中,会继续判断,不满足情况就跳出while,满足就继续wait

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用NIO技术改写Echo项目的客户机/服务器设计的Java代码示例: 服务器端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; public class NioEchoServer { private static final int BUF_SIZE = 1024; private static final int PORT = 8080; private static final int TIMEOUT = 3000; public static void main(String[] args) { selector(); } public static void selector() { Selector selector = null; ServerSocketChannel ssc = null; try { // 创建选择器 selector = Selector.open(); // 打开监听通道 ssc = ServerSocketChannel.open(); // 绑定端口 ssc.socket().bind(new InetSocketAddress(PORT)); // 设置为非阻塞模式 ssc.configureBlocking(false); // 注册选择器并监听接受事件 ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started and listen on port " + PORT + "..."); while (true) { // 等待事件 if (selector.select(TIMEOUT) == 0) { System.out.print("."); continue; } // 获取事件集合 Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); // 处理事件 handleKey(key); iter.remove(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (selector != null) { selector.close(); } if (ssc != null) { ssc.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void handleKey(SelectionKey key) throws IOException { if (key.isAcceptable()) { // 处理接受事件 ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(key.selector(), SelectionKey.OP_READ); } if (key.isReadable()) { // 处理读事件 SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); int len = sc.read(buf); if (len > 0) { buf.flip(); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); String msg = new String(bytes, "UTF-8"); System.out.println("Server received: " + msg); sc.register(key.selector(), SelectionKey.OP_WRITE); // 将读取到的数据写回客户端 ByteBuffer writeBuf = ByteBuffer.wrap(bytes); sc.write(writeBuf); } else if (len == -1) { System.out.println("Client closed..."); sc.close(); } } if (key.isWritable()) { // 处理写事件 SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); sc.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } } } ``` 客户端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class NioEchoClient { private static final int BUF_SIZE = 1024; private static final int PORT = 8080; public static void main(String[] args) { try { // 打开通道 SocketChannel sc = SocketChannel.open(); // 设置为非阻塞模式 sc.configureBlocking(false); // 连接服务器 sc.connect(new InetSocketAddress(PORT)); while (!sc.finishConnect()) { System.out.print("."); } System.out.println("Client connected..."); // 发送数据 ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); buf.put("Hello, NIO!".getBytes()); buf.flip(); sc.write(buf); // 接收数据 buf.clear(); int len = sc.read(buf); if (len > 0) { buf.flip(); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); String msg = new String(bytes, "UTF-8"); System.out.println("Client received: " + msg); } // 关闭通道 sc.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码示例中,服务器端使用Selector监听ACCEPT、READ和WRITE事件,客户端使用SocketChannel与服务器建立连接,并发送和接收数据。通过NIO技术,可以实现多个客户端连接共享少量线程的并发处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值