例一:interrupt方法
public class ThreadDemo01 {
public static void main(String[] args) {
Thread t1=new Thread() {
public void run() {
System.out.println("t1开始");
try {
Thread.sleep(10000);
System.out.println("t1在睡觉");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("t1睡觉被打断");
}
}
};
Thread t2=new Thread() {
public void run() {
for(int i=0;i<5;i++) {
System.out.println("t2:砸墙,"+80*i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t1.interrupt();
}
};
t1.start();
t2.start();
}
}
运行结果:
t2:砸墙,0
t1开始
t2:砸墙,80
t2:砸墙,160
t2:砸墙,240
t2:砸墙,320
java.lang.InterruptedException: sleep interrupted
t1睡觉被打断
at java.lang.Thread.sleep(Native Method)
at com.hyxy0915.ThreadDemo01$1.run(ThreadDemo01.java:8)
例二:线程setPriority方法测试说明
public class ThreadDemo03 {
public static void main(String[] args) {
Thread t1=new Thread() {
public void run() {
for(int i=0;i<10;i++) {
System.out.println("t1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
}
}
};
Thread t2=new Thread() {
public void run() {
for(int i=0;i<10;i++) {
System.out.println("t2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
}
}
};
Thread t3=new Thread() {
public void run() {
for(int i=0;i<10;i++) {
System.out.println("t3");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
}
}
};
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
运行结果:从结果可以看出t1、t2、t3并非按照所设置优先级进行输出,可见,理论上来说线程可以设置优先级,可是cpu是不可控的,所以优先级仅仅只是在理论上,并非是一定按照我们所设置优先级进行cpu调度
例三:join方法示例
public class ThreadDemo04 {
private static int sum=0;
public static void main(String[] args) {
Thread t1=new Thread() {
public void run() {
for(int i=0;i<=100;i++) {
sum+=i;
}
}
};
Thread t2=new Thread() {
public void run() {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum);
}
};
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
输出结果:5050
无论运行多少次结果都为5050,所以我们由此可知是t1线程运行结束后t2才开始运行