join、中断线程
public class test {
public static void main(String[] args){
Thread t_01 = new Thread(new MyRunnable_01());
Thread t_02 = new Thread(new MyRunnable_02());
t_02.start();
for(int i=1;i<21;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
if(i == 10){
t_01.interrupt();
MyRunnable_02.flag = false;
}
Thread.sleep(300);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
}
class MyRunnable_01 implements Runnable {
public void run(){
for(int i=1;i<21;i++){
if(Thread.interrupted()){
break;
}
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(300);
}catch(InterruptedException e){
System.out.println(e);
Thread.currentThread().interrupt();
}
}
}
}
class MyRunnable_02 implements Runnable {
public static boolean flag = true;
int i = 1;
public void run(){
while(flag){
System.out.println(Thread.currentThread().getName()+"--"+i++);
try {
Thread.sleep(300);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
}
守护线程、yield
public class test {
public static void main(String[] args){
Thread t = new Thread(new MyRunnable());
t.setDaemon(true);
t.start();
for(int i=1;i<21;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(250);
}catch(InterruptedException e){
System.out.println(e);
}
if(i==5){
Thread.yield();
}
}
}
}
class MyRunnable implements Runnable {
public void run(){
for(int i=1;i<21;i++){
System.out.println(Thread.currentThread().getName()+"--"+i);
try {
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println(e);
}
}
}
}