操作线程
thread线程停止
- 建议线程正常停止—->利用此时,不建议死循环
- 建议使用标志位—->设置一个标志位
- 不要使用stop或destroy等过时或jdk不建议使用的方法
/**
* 测试停止线程
* 1.建议线程正常停止---->利用此时,不建议死循环
* 2.建议使用标志位---->设置一个标志位
* 3.不要使用stop或destroy等过时或jdk不建议使用的方法
*/
public class TestThredStop implements Runnable {
// 设置一个标志位
private boolean flag = true;
public static void main(String[] args) {
TestThredStop testThredStop = new TestThredStop();
new Thread(testThredStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("i=" + i);
if (i == 900) {
// 调用stop方法停止线程以转换标志位
testThredStop.stop();
System.out.println("线程停止了");
}
}
}
/**
* 设置一个公开的方法用于停止线程,转换标志位
*/
public void stop() {
this.flag = false;
}
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("run正在执行" + i++);
}
}
}
参考资料:
线程休眠
sleep模拟网络延时:放大问题的发生性
/**
* 线程休眠
* 模拟网络延时:放大问题的发生性
*/
public class TestThreadSleep implements Runnable {
private int ticketNums = 10;
public static void main(String[] args) {
TestThreadSleep testThreadSleep = new TestThreadSleep();
new Thread(testThreadSleep, "小明").start();
new Thread(testThreadSleep, "老师").start();
new Thread(testThreadSleep, "黄牛").start();
}
@Override
public void run() {
while (true) {
if (ticketNums <= 0) {
break;
}
try {
// 模拟延迟
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "==> 拿到了第" + ticketNums-- + "张票");
}
}
}
sleep模拟倒计时
/**
* 线程休眠
* 模拟倒计时
*/
public class TestThreadSleep2 {
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 模拟倒计时
* @throws InterruptedException
*/
public static void tenDown() throws InterruptedException {
int num = 10;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
参考资料:
线程礼让(yield)
- 线程礼让是让当前的线程暂停(变为就绪状态),但不阻塞
- 让线程从运行状态转为就绪状态
- 让CPU重新调度,礼让不一定成功(变为就绪状态,可能重新竞争还成功),看CPU心情
/**
*礼让不一定成功
*/
public class TestThreadYield {
public static void main(String[] args) {
MyyYield myyYield = new MyyYield();
new Thread(myyYield, "小明").start();
new Thread(myyYield, "老师").start();
}
}
class MyyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始执行");
// 线程礼让
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程停止执行");
}
}
参考资料:
线程强制执行(join)
会让其他线程阻塞
/**
*线程join方法,可以理解为插队
*/
public class TestThreadJoin implements Runnable {
public static void main(String[] args) throws InterruptedException {
TestThreadJoin testRunnable2 = new TestThreadJoin();
Thread thread = new Thread(testRunnable2, "小明");
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 200) {
// i等于200让thread线程(小明)插队
thread.join();
}
System.out.println(Thread.currentThread().getName() + "main" + i);
}
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "vip线程来了" + i);
}
}
}
参考资料: