目标:线程控制
线程休眠:
Thread.sleep,让当前线程暂停一段时间再继续执行。
public class ThreadControlDemo01 {
public static void main(String[] args) {
for(int i = 0 ; i < 10 ; i++ ){
System.out.println("输出:"+i);
try {
// 项目经理让我加上这行代码,如果用户交钱了就注释掉。
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
线程礼让:
public class ThreadControlDemo02 {
public static void main(String[] args) {
new MyThread().start();
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
if(i == 3){
Thread.yield();// 线程让步,当前线程让出CPU。
}
}
}
class MyThread extends Thread{
@Override
public void run() {
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
}
}
}
join线程:
当前线程让某个线程插入进来执行。
public class ThreadControlDemo03 {
public static void main(String[] args) {
Thread t = new MyThread01();
t.start();
Thread t1 = new MyThread01();
t1.start();
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
if(i == 3){
try {
t.join(); // 主线程执行到3的时候,让t线程来跑,但是可能之后被别人抢走
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class MyThread01 extends Thread{
@Override
public void run() {
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
}
}
}
线程优先级:
可以为某个线程设计优先级,优先级高的线程有更多的机会得到CPU。
– public final int getPriority() : 获取优先级。
– public final void setPriority(int newPriority):设置优先级
线程有三个优先级别:
1 MIN_PRIORITY
5 NORM_PRIORITY (默认)
10 MAX_PRIORITY
public class ThreadControlDemo04 {
public static void main(String[] args) {
Thread t = new MyThread02();
//System.out.println(t.getPriority());
t.setPriority(Thread.MAX_PRIORITY);
t.start();
Thread t1 = new MyThread02();
//System.out.println(t1.getPriority());
//t1.setPriority(Thread.NORM_PRIORITY); // 默认
t1.start();
System.out.println(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
}
}
}
class MyThread02 extends Thread{
@Override
public void run() {
for(int i = 0 ; i < 100 ; i++ ){
System.out.println(Thread.currentThread().getName()+" => " + i);
}
}
}