package com.wen.thread;
/**
* @Author WangEn
* @CreateTime: 2021-04-10-18-20
* @Emile: wen_5988@163.com
*/
// 模拟网络延迟 :放大问题的发生性。找到代码的不足
// 发现会抢资源
public class TestSleep implements Runnable {
private int tick = 10;
@Override
public void run() {
while (true){
if (tick<=0){
break;
}
// 模拟网络延迟
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+tick--+"张票");
}
}
public static void main(String[] args) {
new Thread(new TestSleep(),"小米").start();
new Thread(new TestSleep(),"黄牛").start();
new Thread(new TestSleep(),"小菜").start();
}
}
// ——----------------------------------------------------------------
package com.wen.thread;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author WangEn
* @CreateTime: 2021-04-10-18-30
* @Emile: wen_5988@163.com
*/
// 模拟倒计时
public class TestSleep2 implements Runnable {
private int num = 10;
/*public static void main(String[] args) {
TestSleep2 ts = new TestSleep2();
new Thread(ts).start();
}*/
public static void main(String[] args) {
Date time = new Date(System.currentTimeMillis()); // 获取系统时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:ss:mm:ss").format(time));
time = new Date(System.currentTimeMillis()); // 重新获取时间赋值
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("倒计时"+num--);
if (num<=0){
break;
}
}
}
}
package com.wen.thread;
/**
* @Author WangEn
* @CreateTime: 2021-04-10-17-50
* @Emile: wen_5988@163.com
*/
/*
停止线程:
1.推荐让线程自己停下来
2.建议使用一个标识位进行终止变量当 flag = false的时候,终止线程
3.不推荐使用JDK自带的stop()方法、destory() 有bug
*/
public class TestStopThread implements Runnable {
private boolean flag = true;
public void stop(){
this.flag = false;
}
@Override
public void run() {
int i = 0;
while (flag) { // 线程二
System.out.println("running...."+i++);
}
}
public static void main(String[] args) {
TestStopThread testStopThread = new TestStopThread();
// 启动线程
new Thread(testStopThread).start();
for (int i = 0; i < 100; i++) { // 主线程
System.out.println("main"+i);
if (i==91){
testStopThread.stop();
System.out.println("线程停止了-->");
}
}
}
}
原文:https://www.cnblogs.com/WangEn/p/14647101.html