public class ThreadTest
implements Runnable {
private static int j=0
;
Object object =
new Object();
private String name;
private ThreadTest(String name)
{
this.name=
name;
}
public static void main(String[] args)
throws InterruptedException{
Thread t1 =
new Thread(
new ThreadTest("xu"
));
Thread t2 =
new Thread(
new ThreadTest("shi"
));
t2.start();
System.out.println("hhh"
);
t1.start();
// t2.notify();
}
public void run(){
synchronized (object) {
for (
int i = 0; i < 10; i++
) {
try {
object.wait(100);
//Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}catch (IllegalMonitorStateException e){
//e.printStackTrace();
}
j++
;
System.out.println(i +
name);
}
}
}
}
wait时结果如下
hhh0shi0xu1shi1xu2shi2xu3shi3xu4xu4shi5shi5xu6xu6shi7shi7xu8xu8shi9shi9xu
sleep时结果如下
hhh0shi0xu1xu1shi2xu2shi3shi3xu4xu4shi5shi5xu6shi6xu7xu7shi8xu8shi9xu9shi
显然,sleep()实现了线程并发,wait()也同样。
注意:wait()是Object的方法,sleep()是Thread的静态方法。
转载于:https://www.cnblogs.com/BBchao/p/7884683.html