如题,
public class MyClass implements Runnable{
public static void main(String[] args) {
MyClass m1 = new MyClass();
Thread t1 = new Thread(m1);
t1.start();
MyClass m2 = new MyClass();
Thread t2 = new Thread(m2);
t2.start();
m1.mySleep();
m2.mySleep();
} public void mySleep() {
try {
Thread.sleep(5000);
System.out.println("Sleep / Run");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run");
}
}输出:
Run
Run
Sleep / Run
Sleep / Run第一个Sleep / Run等待了5秒,第二个Sleep / Run在第一个出现后,又等了5秒。
我想问的是,有没有方法可以使得两个线程同时休眠。而不是第一个线程休眠,休眠完之后,在休眠第二个。
public class MyClass implements Runnable{
public static void main(String[] args) {
MyClass m1 = new MyClass();
Thread t1 = new Thread(m1);
t1.start();
MyClass m2 = new MyClass();
Thread t2 = new Thread(m2);
t2.start();
m1.mySleep();
m2.mySleep();
} public void mySleep() {
try {
Thread.sleep(5000);
System.out.println("Sleep / Run");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run");
}
}输出:
Run
Run
Sleep / Run
Sleep / Run第一个Sleep / Run等待了5秒,第二个Sleep / Run在第一个出现后,又等了5秒。
我想问的是,有没有方法可以使得两个线程同时休眠。而不是第一个线程休眠,休眠完之后,在休眠第二个。
m1.mySleep();
m2.mySleep();
”sleep是针对谁sleep?不是你的m1,m2,而是当前执行线程。你的m1,m2根本就没有sleep
System.out.println("Sleep / Run")这句再打印点线程名相关的东西:
System.out.println("Sleep / Run," + Thread.currentThread.....);
你的这个sleep 睡都是在主函数 而应该是
package 解答;public class TestThread implements Runnable{
public static void main(String[] args) {
TestThread m1 = new TestThread();
Thread t1 = new Thread(m1);
t1.start();
try {
Thread.sleep(5000);
System.out.println("main sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
} public void run() {
try {
Thread.sleep(5000);
System.out.println("thread / Run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(2);
for(int i = 0; i< 2; i++){
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(5000L);
System.out.println("Sleep / Run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
startSignal.countDown();
System.out.println("begin sleep !");
startSignal.await();
}}
具体参阅一下文档 CountDownLatch JDK的新特性
CountDownLatch startSignal = new CountDownLatch(1);
for(int i = 0 ; i< 2 ; i++){
new Thread(new SleepTask(startSignal)).start();
}
Thread.sleep(2000L);
System.out.println("begin......");
startSignal.countDown();
}}class SleepTask implements Runnable {
private CountDownLatch downLatch; SleepTask(CountDownLatch downLatch) {
this.downLatch = downLatch;
} public void run() {
try {
downLatch.await();
Thread.sleep(5000L);
System.out.println("Sleep/run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}}