线程命名
package java1;
import java.util.concurrent.ExecutionException;
class MyThread implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class L1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread mt =new MyThread();
new Thread(mt,"线程A").start();
new Thread(mt,"线程B").start();
new Thread(mt).start();
}
}
主线程负责整体流程,子线程负责耗时操作。
线程休眠
package java1;
import java.util.concurrent.ExecutionException;
public class L1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Runnable run =() -> {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+"i="+i);
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(run,"线程").start();
}
}
线程中断
package java1;
public class L1 {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(()-> {
System.out.print("我要睡觉了\n");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("找死,敢打扰我睡觉!");
}
});
thread.start();
Thread.sleep(100);
if(!Thread.interrupted()) {
System.out.println("老张,别睡了!");
thread.interrupt();
}
}
}
线程强制运行
package java1;
public class L1 {
public static void main(String[] args) throws Exception {
Thread mainthread=Thread.currentThread();//获得主线程
Thread thread = new Thread(()-> {
for(int i=0;i<50;i++) {
if(i>3) {//霸道线程来了
try {
mainthread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("同学"+i+"我要出去玩");
}
});
thread.start();
for(int i=0;i<50;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("霸道同学"+i+"先出去玩");
}
}
}
线程礼让
public class Two_7 {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(()-> {
for(int i=0;i<50;i++) {
if(i%3==0) {
Thread.yield();
System.out.println("######");
}
System.out.println(Thread.currentThread().getName()+i+"我要出去玩");
}
},"普通同学");
thread.start();
for(int i=0;i<50;i++) {
thread.sleep(100);
System.out.println("霸道同学"+i+"先出去玩");
}
}
}
线程优先级
public class Two_7 {
public static void main(String[] args) throws Exception {
Runnable run=()-> {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+"执行");
}
};
Thread threadA=new Thread(run,"线程A");
Thread threadB=new Thread(run,"线程B");
Thread threadC=new Thread(run,"线程C");
threadA.setPriority(Thread.MIN_PRIORITY);
threadB.setPriority(Thread.MAX_PRIORITY);
threadA.setPriority(Thread.NORM_PRIORITY);
//不一定优先级最高,抢占资源最快,但是概率提升
threadA.start();
threadB.start();
threadC.start();
}
}