线程
线程的状态
- 创建状态
- 就绪状态
- 运行状态
- 堵塞状态
- 死亡状态
线程的方法
线程停止
public class Stop implements Runnable{
private boolean flag=true;
public static void main(String[] args) {
Stop thread=new Stop();
new Thread(thread).start();
for(int i=0;i<1000;i++){
System.out.println(i);
if(i==800){
thread.stop();
System.out.print("线程改结束了\n");
}
}
}
public void run() {
while(flag){
System.out.println("Run...");
}
}
public void stop(){
this.flag=false;
}
}
线程停止
public class Join implements Runnable{
public static void main(String[] args) throws InterruptedException {
Join join=new Join();
Thread thread= new Thread(join);
thread.start();
for (int i =0; i < 200; i++) {
if(i==150)thread.join();
System.out.println("普通用户"+i);
}
}
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("ViP来了"+i);
}
}
}
线程礼让
public class Yield implements Runnable{
public static void main(String[] args) {
Yield yield=new Yield();
new Thread(yield,"a").start();
new Thread(yield,"b").start();
}
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始了");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程结束了");
}
}
线程休眠
Thread.sleep(1000)