java notifyondataavailable_Java多线程sleep(),join(),interrupt(),wait(),notify()

5.5.2 Preemption

Every virtual machine has a thread scheduler that determines which thread to run at any given time. There are two kinds of thread scheduling: preemptive and cooperative. A preemptive thread scheduler determines when a thread has had its fair share of CPU time, pauses that thread, and then hands off control of the CPU to a different thread. A cooperative thread scheduler waits for the running thread to pause itself before handing off control of the CPU to a different thread. A virtual machine that uses cooperative thread scheduling is much more susceptible to thread starvation than a virtual machine that uses preemptive thread scheduling, since one high-priority, uncooperative thread can hog an entire CPU.

All Java virtual machines are guaranteed to use preemptive thread scheduling between priorities. That is, if a lower-priority thread is running when a higher-priority thread becomes able to run, the virtual machine will sooner or later (and probably sooner) pause the lower-priority thread to allow the higher-priority thread to run. The higher-priority thread preempts the lower-priority thread.

The situation when multiple threads of the same priority are able to run is trickier. A preemptive thread scheduler will occasionally pause one of the threads to allow the next one in line to get some CPU time. However, a cooperative thread scheduler will not. It will wait for the running thread to explicitly give up control or come to a stopping point. If the running thread never gives up control and never comes to a stopping point and if no higher-priority threads preempt the running thread, all other threads will starve. This is a bad thing. It's important to make sure all your threads periodically pause themselves so that other threads have an opportunity to run.

There are 10 ways a thread can pause in favor of other threads or indicate that it is ready to pause. These are:

It can block on I/O.

It can block on a synchronized object.

It can yield.

It can go to sleep.

It can join another thread.

It can wait on an object.

It can finish.

It can be preempted by a higher-priority thread.

It can be suspended.

It can stop.

You should inspect every run( ) method you write to make sure that one of these conditions will occur with reasonable frequency. The last two possibilities are deprecated because they have the potential to leave objects in inconsistent states, so let's look at the other eight ways a thread can be a cooperative citizen of the virtual machine.

5.5.2.1 Blocking

Blocking occurs any time a thread has to stop and wait for a resource it doesn't have. The most common way a thread in a network program will voluntarily give up control of the CPU is by blocking on I/O. Since CPUs are much faster than networks and disks, a network program will often block while waiting for data to arrive from the network or be sent out to the network. Even though it may block for only a few milliseconds, this is enough time for other threads to do significant work.

Threads can also block when they enter a synchronized method or block. If the thread does not already possess the lock for the object being synchronized on and some other thread does possess that lock, the thread will pause until the lock is released. If the lock is never released, the thread is permanently stopped.

Neither blocking on I/O nor blocking on a lock will release any locks the thread already possesses. For I/O blocks, this is not such a big deal, since eventually the I/O will either unblock and the thread will continue or an IOException will be thrown and the thread will then exit the synchronized block or method and release its locks. However, a thread blocking on a lock that it doesn't possess will never give up its own locks. If one thread is waiting for a lock that a second thread owns and the second thread is waiting for a lock that the first thread owns, deadlock results.

回复  更多评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中使用RXTX库来操作串口,可以通过多线程来实现同时处理多个串口通信任务的需求。下面是一个简单的使用RXTX库实现串口多线程通信的示例代码: ``` import gnu.io.*; public class SerialPortThread implements Runnable, SerialPortEventListener { private SerialPort serialPort; private Thread thread; private String portName; private int baudRate; private boolean running; public SerialPortThread(String portName, int baudRate) { this.portName = portName; this.baudRate = baudRate; this.running = false; } public void start() { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); thread = new Thread(this); thread.start(); } else { throw new Exception("Error: Only serial ports are handled by this example."); } } catch (Exception e) { System.out.println("Error: " + e); } } public void stop() { running = false; serialPort.removeEventListener(); serialPort.close(); thread.interrupt(); } @Override public void run() { running = true; while (running) { try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Thread interrupted: " + e); } } } @Override public void serialEvent(SerialPortEvent serialPortEvent) { if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { // 读取串口数据 byte[] buffer = new byte[serialPort.getInputStream().available()]; int len = serialPort.getInputStream().read(buffer); System.out.println("Received " + len + " bytes: " + new String(buffer)); } catch (Exception e) { System.out.println("Error: " + e); } } } } ``` 这个例子实现了一个SerialPortThread类,它可以监听一个串口并在收到数据时打印出来。要使用它,你可以在你的应用程序中创建多个SerialPortThread对象并调用start()方法来开始监听串口。例如: ``` SerialPortThread port1 = new SerialPortThread("/dev/ttyUSB0", 9600); SerialPortThread port2 = new SerialPortThread("/dev/ttyUSB1", 9600); port1.start(); port2.start(); ``` 这将创建两个SerialPortThread实例并开始监听/dev/ttyUSB0和/dev/ttyUSB1串口。在运行时,你将看到在多个线程中同时接收串口数据的输出。记得在程序结束时调用stop()方法来停止所有线程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值