一、线程等待
一般而言,只有等待一个线程结束,才能执行下一步的工作,那么就需要一个线程结束的标志,
即jion方法:
public class Demon1 {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
//Object lock2 = new Object();
Thread t1 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
count++;
}
System.out.println("t1结束");
});
Thread t2 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
count++;
}
System.out.println("t2结束");
});
t1.start();
t1.join();
t2.start();
t2.join();
System.out.println(count);
}
}
其实这个方法很好理解,但如果将上述代码进行一些更改,会发现得不到想要的结果:
public class Demon1 {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
//Object lock2 = new Object();
Thread t1 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
count++;
}
System.out.println("t1结束");
});
Thread t2 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
count++;
}
System.out.println("t2结束");
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}
输出的结果实际上是大于50000的随机数,每次结果都不一样,因为操作系统线程是并发执行的,当两个线程同时对同一个变量执行相同操作时,会发生一些问题,可能同一时刻发生了多次自增,但结果呈现的只是一次自增,解决方法有两种,一种是前面的,即每个线程start后就立刻join,参这样会让其变成单例模式,第二种是采取加锁,确保每个线程完成自增后才能进行下次任务:
public class Demon1 {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
//Object lock2 = new Object();
Thread t1 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
synchronized(lock){
count++;
}
//count++;
}
System.out.println("t1结束");
});
Thread t2 = new Thread(()->{
for (int i = 0; i < 50000; i++) {
synchronized(lock) {
count++;
}
//count++;
}
System.out.println("t2结束");
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}
二、线程休眠
其实前面已经多次使用过线程休眠了
其实需要注意的不多,前面使用大部分是为了方便观察输出结果,只有一点需要注意,即休眠时间只能大于等于系统设置的时间。详细代码可以运行Thread(上)的内容。
三、获取线程实例
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
这个方法可以得到线程的代号名称,也可链接本地自行查看。