我想有一个布尔值来通知系统某些特定服务启动的部分.
由于一些奇怪的原因,我收到了错误java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll().
奇怪的是,notifyAll()位于一个synchronized块内,该块控制我调用notifyAll()的对象.
我的班级开头是这样的:
public class MyService {
public static Boolean notifier = Boolean.valueOf(false);
@Override
public void start() {
synchronized (MyService.notifier) {
MyService.notifier = Boolean.valueOf(true);
MyService.notifier.notifyAll();
}
}
@Override
public void stop() {
synchronized (MyService.notifier) {
MyService.notifier = Boolean.valueOf(false);
MyService.notifier.notifyAll();
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
我正在研究一个Android应用程序.我认为它不应该影响任何事情,但是如果影响java的工作方式,我会用该注释补充问题.
如果对象锁定在同步块中,为什么会出现异常?
java multithreading synchronization synchronized java-threads
在我的应用程序中我有按钮,单击时将查询数据库并在屏幕上显示结果.查询操作通常需要1~3秒.这些按钮将经常被点击.
我已经在AsyncTask和Thread上实现了这个动作,但看起来差别很小.
但是从长远来看,尤其是在按钮被多次点击时,这在资源(CPU,内存)方面会更有益吗?
我有一个方法可以在执行 Groovy 脚本后返回 HTTP 响应。我创建了一个匿名线程来执行 Groovy 脚本。但是,作为预防措施,我希望线程在 3 秒后停止,以防止不良脚本(即:无限循环)继续运行。
public Response runScript(String script) {
GroovyShell shell = new GroovyShell();
Thread thread = new Thread() {
public void run() {
Script validatedScript = shell.parse(script);
validatedScript.run();
}
};
thread.start();
thread.join(3000);
return Response.ok("It ran!", MediaType.TEXT_PLAIN).build();
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于没有无限循环的脚本。但是,如果存在无限循环,则响应“It ran!” 已交付给客户端,但线程仍处于活动状态。我如何在之后杀死这个线程join()?
class Test {
boolean isFirstThread = true;
private synchronized void printer(int threadNo) {
if(isFirstThread) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isFirstThread = false;
System.out.println(threadNo);
}
public void starter() {
new Thread(){
@Override()
public void run() {
printer(0);
}
}.start();
new Thread(){
@Override()
public void run() {
printer(1);
}
}.start();
new Thread(){
@Override()
public void run() {
printer(2);
}
}.start();
new Thread(){
@Override()
public void run() {
printer(3);
}
}.start();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,当我从main调用starter时.我创建了四个新的线程来调用同步函数.我知道无法预测线程的执行顺序.除非它们都等待一段时间,否则第一个线程可以完成并从同步块中退出.在这种情况下,我希望所有线程都保持在一个队列,所以我希望答案为
0
1 …
我有以下服务代码,我在其中启动了一个线程,负责在消息传入时分派消息。
public void run() {
while (! Thread.interrupted()) {
try {
Message msg = null;
synchronized (_queue) {
if (_queue.size() == 0) {
_queue.wait(10000);
}
if (_queue.size() != 0) {
msg = _queue.poll();
}
if (msg != null) {
_dispatcher.dispatch(msg);
}
}
}
catch (InterruptedException i) { }
catch (Exception e) { }
}
}
public void add (final Message m){
if (m == null)
return;
synchronized (_queue){
_queue.add(m);
_queue.notify();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当这段代码在我的 android 模拟器上运行时,我收到了很多如下警告:
Long monitor contention event with …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个代码,当它与我的计算机在同一网络上时,它将返回我的覆盆子的IP.这个想法是让它像Samba一样进行广播(广播解析是最接近原始NetBIOS机制的.基本上,寻找名为Trillian的服务的客户会喊出"哟!Trillian!你在哪里?",等待具有该名称的机器以IP地址回答.来源:Samba团队)
所以这是代码:
public class GetIP {
static String url; //global so I can access it after the threads are finished
public class CheckIP extends Thread {
private String url_test;
public CheckIP(String url_t) {
url_test = url_t;
}
public void run(){
try {
result = getHTML(this.url_test); //result = the response from the GET request to this.url_test
} catch (Exception e) {
}
if(result <is what I want>) {
url = this.url_test
System.out.println("Flag 1");
<I'd like to do something here, preferebly kill …Run Code Online (Sandbox Code Playgroud) 我有一个模块,必须检查特定目录的新文件(Create).该文件将由另一个我无法控制或可见的系统创建.
我使用了Java WatchService API,当创建新文件时,我能够获得事件ENTRY_CREATE.下面是代码.
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(dirLocation);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
if ("ENTRY_CREATE".equalsIgnoreCase(event.kind().name())) {
// File reading here
}
Run Code Online (Sandbox Code Playgroud)
问题是在尝试读取新文件的某个时候,我正在获取空内容而没有任何异常.搜索Google和SO,我发现如果文件写入不完整,可能会发生这种情况.为了解决这个问题,我尝试了随机访问文件,锁定并创建了FileOutputStream,但没有运气,我得到了空的内容,没有任何例外.最后我尝试了下面的工作.但我担心的是,这必须在单独的线程内部进行检查,以便不阻塞WatchService事件,并且线程数量可以随着文件数量的增长而增长,也可能是更昂贵的操作.
closed = file.renameTo(file);
Run Code Online (Sandbox Code Playgroud)
有没有其他有效的方法来检查文件写入操作是否完成?或者是否有任何API可以处理这个?
我在分析 vaadin 7.0 JAVA 应用程序的线程转储和用 Spring MVC 编写的集成层时遇到困难。处于等待状态的线程过多,导致应用程序在高峰时段变慢,并导致简单代码的执行延迟长达 10 秒。以下是等待线程中出现的跟踪:-
priority:5 - threadId:0x00007f98b48de800 - nativeId:0x6511 - nativeId (decimal):25873 - state:WAITING
stackTrace:
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000006d5444af0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)
我在应用程序的许多地方使用 API 轮询,以下是我如何进行 API 轮询的代码:-
@Override
public void run()
{
int counter = 1;
while (true)
{
try
{
if (counter == 1)
Thread.sleep(5000);
else
Thread.sleep(10000);
System.out.println("Call Some API");
if (counter …Run Code Online (Sandbox Code Playgroud) 我使用 ScheduledExecutorService 在经过一段时间后将事件重新排队回到消息队列中。现在我需要在触发某个事件后执行该执行器的所有计划的挂起任务。
我已经看到可以取消挂起的任务,但我需要在执行器关闭之前运行所有这些任务。有没有办法做到这一点?或者我应该使用不同的策略来安排此任务。
java-threads ×10
java ×8
android ×3
continue ×1
groovy ×1
java-7 ×1
jstack ×1
synchronized ×1
throw ×1
try-catch ×1
vaadin7 ×1
watchservice ×1