多线程常用操作方法
1.
2.
线程的休眠测试:
Runnable runnable = () -> {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 5; i++) {
new Thread(runnable, "线程" + i).start();
}
/*
线程0
线程1
线程2
线程3
线程4
线程4
线程3
线程2
线程1
线程0
线程3
线程0
线程4
线程2
线程1
*/
- 线程的中断
Thread thread = new Thread(() -> {
System.out.println("开始执行睡眠");
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
System.out.println("线程中断");
}
});
thread.start();
if (!thread.isInterrupted()) {
thread.interrupt();
}
/*
开始执行睡眠
线程中断
*/
-
线程的强制执行
满足于某些条件之后,某个线程对象可以一直独占资源,一直到该线程程序执行结束。
未加强制执行的示例:
final int NUM = 5; Thread aThread = new Thread(() -> { for (int i = 0; i < NUM; i++) { System.out.println(Thread.currentThread().getName()); } }, "A线程"); Thread bThread = new Thread(() -> { for (int i = 0; i < NUM; i++) { System.out.println(Thread.currentThread().getName()); } }, "B线程"); aThread.start(); bThread.start(); /* A线程 B线程 A线程 B线程 B线程 B线程 B线程 A线程 A线程 A线程 */ // 执行顺序符合并发执行的不可见性
加上强制执行示例:
final int NUM = 5; Thread aThread = new Thread(() -> { for (int i = 0; i < NUM; i++) { System.out.println(Thread.currentThread().getName()); } }, "A线程"); Thread bThread = new Thread(() -> { try { aThread.join(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + "被中断"); } for (int i = 0; i < NUM; i++) { System.out.println(Thread.currentThread().getName()); } }, "B线程"); aThread.start(); bThread.start(); /* A线程 A线程 A线程 A线程 A线程 B线程 B线程 B线程 B线程 B线程 */ // 始终A线程在前
-
线程的礼让
针对某一线程的某一特定时期或者某一特定条件,可以先让资源让出去让别的线程先执行。
使用
public static void yield()
方法可以实现礼让。Thread thread = new Thread(() -> { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { Thread.yield(); System.out.println("礼让"); } System.out.println(Thread.currentThread().getName()); } }); thread.start(); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()); } /* main main main 礼让 Thread-0 Thread-0 礼让 Thread-0 Thread-0 礼让 Thread-0 Thread-0 礼让 Thread-0 Thread-0 礼让 Thread-0 Thread-0 main main */
-
线程优先级
线程优先级越高越有可能执行。
示例:
Runnable runnable = () -> { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()); } }; Thread aThread = new Thread(runnable, "线程A"); Thread bThread = new Thread(runnable, "线程B"); Thread cThread = new Thread(runnable, "线程C"); aThread.setPriority(Thread.MIN_PRIORITY); bThread.setPriority(Thread.MAX_PRIORITY); cThread.setPriority(Thread.NORM_PRIORITY); aThread.start(); bThread.start(); cThread.start(); /* 线程C 线程C 线程C 线程C 线程C 线程A 线程A 线程A 线程B 线程B 线程B 线程B 线程B 线程A 线程A */
优先级越高越有可能执行,但是只是概率增加,并不一定。