线程强制执行
package threadLearn.state;
//测试Join方法 ——>想象成插队
public class testJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程vip来了——>"+i);
}
}
public static void main(String[] args) throws InterruptedException {
testJoin testJoin = new testJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 500; i++) {
//插队
if (i==200) {
thread.join();
}
System.out.println("main"+i);
}
}
}
观测线程状态
package threadLearn.state;
//观察测试线程状态
public class testState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("");
}
});
//观测状态
Thread.State state =thread.getState();
System.out.println(state);//New
//观察启动后
thread.start();//启动线程
state=thread.getState();//获取线程状态
System.out.println(state);//Run
while (state!= Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
线程优先级
可能出现性能倒置的现象
package threadLearn.state;
public class testPriority {
public static void main(String[] args) {
//转线程默认优先级
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
//会报错
t5.setPriority(-1);
t5.start();
//会报错,可以注释掉,仅仅是展示优先级是有范围的
t6.setPriority(11);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
输出
main--->5
Thread-1--->1
Thread-0--->5
Thread-3--->10
Thread-2--->4
守护线程
package threadLearn.state;
//测试守护线程
public class testDaemon {
public static void main(String[] args) {
Knight knight = new Knight();
You you = new You();
Thread thread = new Thread(knight);
thread.setDaemon(true);//默认是false,表示是用户线程,正常的线程都是用户线程
thread.start();//守护线程启动
new Thread(you).start();//用户线程启动
}
}
//骑士 守护线程
class Knight implements Runnable{
@Override
public void run() {
while (true){
System.out.println("骑士保护着你");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("==============goodbye world====================");
}
}