单线程睡眠问题 我现在遇到个问题,就是我的框架是单线程的,所以不能用Threed.sleep()这种方式,但我的程序又不方便用JAVA的定时器。原因我需要在同一方法中System.out.println()后延迟1分钟再打印另一个System.out.println(),我现在的做法是用while循环对比时间,但如果同时有一百个对象这样做的话会对CUP损耗较大,大家有没有更好的方法呢。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 public class Mytest { public void print() { System.out.println("123"); } public void print2() { System.out.println("1234"); } public static void main(String[] arg) throws InterruptedException { Mytest test = new Mytest(); test.print(); synchronized(test){ test.wait(2000); } test.print2(); }} 为什么单线程就不能用Thread.sleep() ? 好像不行啊,会报java.lang.IllegalMonitorStateException的错,我的程序是这样测试的。Thread t = new Thread(){ TestObj t1 = new TestObj(); TestObj t2 = new TestObj(); public void run() { while(true) { try { Thread.sleep(1000); t1.print("1"); t2.wait(2000); t2.print("2"); } catch (InterruptedException e) { e.printStackTrace(); } } } }; t.start(); 单线程sleep其它的对象就不工作了 是没有加synchronized报的错,但还是不行,t2对象等待后还是会整个线程还是会等待,我想实现的是t1不断打印,t2迟5秒后再打印,也就是说t1一定打印得比t2多,但现在不是这效果。 没有timer就自己实现一个timer呗timer的本质还不就是循环计时。//实现自己的timerclass MyTimer { //用于累加周期,我就不考虑数据溢出啥的了,估计也溢出不了 long start = 0L; long end = 0L; //控制时钟周期 final long invet = 2000L; //这个运算可能要消耗1ms 忽略不计 boolean action() { start = System.currentTimeMillis(); if (start > end) { end = start + invet; return true; } else { return false; } }}public class TimerTest{ public static void main(String[] args) throws Exception { MyTimer timer = new MyTimer(); while (true) { System.out.println("t1"); if (timer.action()) { System.out.println("t2-------------------我来了"); //为了方便看效果,停一下 Thread.sleep(100); } } }} 急求答案 高手帮忙解释下一个很短的程序 如何把字符串"1.2.3.4.5.6."中的每一个数字分别提取出来?用for语句 怎么将ACCESS中的OLE图片对象导出一个图片文件? arraylist类问题? 画图并保存 请教怎样将一个list里的数据读入一个string里. 劳驾各位大侠帮我搞定时不时弹出的窗口 怎么用Javadoc来制作Java帮助文档? 我想使用Java Applet连编制一个Chart程序,请问怎样实现? CSS,求赐教!!! java实现对bmp图片的旋转问题,为什么只能实现旋转一次,求解答
public void print() {
System.out.println("123");
} public void print2() {
System.out.println("1234");
} public static void main(String[] arg) throws InterruptedException {
Mytest test = new Mytest();
test.print();
synchronized(test){
test.wait(2000);
}
test.print2();
}
}
TestObj t1 = new TestObj();
TestObj t2 = new TestObj();
public void run() {
while(true) {
try {
Thread.sleep(1000);
t1.print("1");
t2.wait(2000);
t2.print("2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
timer的本质还不就是循环计时。//实现自己的timer
class MyTimer
{
//用于累加周期,我就不考虑数据溢出啥的了,估计也溢出不了
long start = 0L;
long end = 0L;
//控制时钟周期
final long invet = 2000L;
//这个运算可能要消耗1ms 忽略不计
boolean action()
{ start = System.currentTimeMillis(); if (start > end)
{
end = start + invet;
return true;
}
else
{
return false;
}
}
}public class TimerTest
{
public static void main(String[] args) throws Exception
{
MyTimer timer = new MyTimer();
while (true)
{
System.out.println("t1"); if (timer.action())
{
System.out.println("t2-------------------我来了");
//为了方便看效果,停一下
Thread.sleep(100);
}
}
}
}