publicstaticvolatileint count = 0 ;
publicstaticvoidmain(String[] args) {
Thread thread1 = new Thread(
()->{
try {
System.out.println(System.currentTimeMillis() + " thread1 is sleep ");
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
for(count = 0; count < 5; count ++){
if (Thread.currentThread().isInterrupted()) {
break;
}
}
System.out.println(System.currentTimeMillis() + " thread1 is end");
}
,"thread1");
thread1.start();
thread1.yield(); //让出cpu 还是thread1先执行完毕
System.out.println(count);
Thread thread2 = new Thread(
()->{
System.out.println(System.currentTimeMillis() + " thread2 is running");
for(count = 5; count < 10; count ++){
try {
thread1.join(); //等待thread1
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (Thread.currentThread().isInterrupted()) {
break;
}
}
System.out.println(System.currentTimeMillis() + " thread2 is end");
}
,"thread2");
thread2.start();
try {
thread2.join(); //等待thread2
thread2.yield(); //让出cpu 还是thread2执行完毕后 main执行完毕
} catch (InterruptedException e) {
}
System.out.println(count);
}
//输出01495808271330 thread1 is sleep
1495808271330 thread2 is running
1495808274330 thread1 is end
1495808274330 thread2 is end
10
等待/唤醒
//wait :挂起线程,
//notify: 随机唤醒挂起的线程
publicstatic Object lock=new Object();
publicstaticvoidmain(String[] args) {
new Thread(
() -> {
synchronized (lock) {
System.out.println(System.currentTimeMillis() + " thread1 is start");
try {
System.out.println(System.currentTimeMillis() + " thread1 is wait ");
lock.wait(); //挂起线程
System.out.println(System.currentTimeMillis() +" now thread1 is running again");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + " thread1 is end");
}
}
).start();
new Thread(
() -> {
synchronized (lock) {
System.out.println(System.currentTimeMillis() + " thread2 is start");
System.out.println(System.currentTimeMillis() + " thread2 is notify thread1 ");
lock.notify(); //随机唤醒挂起线程,挂起线程具备执行资格
System.out.println(System.currentTimeMillis() + " thread2 is end");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
).start();
}
//输出1495808342892 thread1 is start
1495808342892 thread1 is wait
1495808342892 thread2 is start
1495808342892 thread2 is notify thread1
1495808342892 thread2 is end
守护线程
//守护线程,主线程执行完毕即停止
publicstaticvoidmain(String[] args) {
Thread thread=new Thread(
()->{
while (true) {
System.out.println(" daemon thread is running");
}
}
);
thread.setDaemon(true); //设置守护main线程
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" main thread is end ");
}
//输出
daemon thread is running
daemon thread is running
daemon thread is running
daemon thread is running
main thread is end