【一】题目要求:
先输出10 个hello,然后是10 个world,不希望交替输出hello和world
【二】样例输出:
或着
方法一:使用join()--->具有延迟的作用,适用固定的顺序。
public class Example extends Thread {
private String data;
public Example(String data) {
this.data = data;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (Exception e) {
}
System.out.print(data+" " );
}
System.out.println();
}
public static void main(String args[]) throws InterruptedException {
Thread t1 = new Example("hello");
Thread t2 = new Example("world");
t1.start();
t1.join();//等待t1执行完毕,在执行t2
t2.start();
}
}
方法二:使用synchronized()--->上锁,当一个线程运行完之后,再运行另一个线程,但是两个线程的前后顺序不确定。
public class Example extends Thread {
private String data;
public Example(String data) {
this.data = data;
}
public void run() {
synchronized (Example.class) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (Exception e) {
}
System.out.print(data+" ");
}
System.out.println();
}
}
public static void main(String args[]) throws InterruptedException {
Thread t1 = new Example("hello");
Thread t2 = new Example("world");
t1.start();
t2.start();
}
}
在使用synchronized()的时候,我犯了一个错误,我在synchronized()中锁住的对象为data,得到的结果都是hello和world交错出现的。后来发现自己锁的对象有问题,因为t1和t2的共同对象不是data,而是Example.class这个类。
日常鸡汤:不轻易用过去来衡量生活的幸与不幸,每个人的生命都可以绽放美丽,只要你珍惜。。。