1.线程的五大状态
详细状态
1.1线程停止,建议使用标志位
public class ThreadStop implements Runnable{
//标志位
private boolean flag = true;
@Override
public void run() {
int i =0;
while (flag){
System.out.println("i am thread" + i++);
}
}
//更改状态
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
ThreadStop stop = new ThreadStop();
new Thread(stop).start();
for (int i = 0; i < 300; i++) {
System.out.println("thread is main"+ i);
if (i == 280){
stop.stop();
System.out.println("thread is stop....."+ i);
}
}
}
}
1.3线程休眠Thread.sleep(int);
public class ThreadSleep {
public static void main(String[] args) {
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
System.out.println(time);
date = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1.4线程优先级
优先级低只代表cpu调度低,有时也可能先执行优先级低的线程
2.初识并发问题,当多个线程操作同一个对象时,出现线程不安全问题
**
* 多线程操作同时操作同一个对象
* 初识并发问题
*/
public class ThreaDemo02 implements Runnable{
private int ticketNums = 10;
@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--+"票");
}
}
public static void main(String[] args) {
ThreaDemo02 tread = new ThreaDemo02();
new Thread(tread,"小梦").start();
new Thread(tread,"黄牛党").start();
new Thread(tread,"老师").start();
}
}
结果:出现重复或者不正确票数