线程停止,最好不要用系统给定的方法,而是自己设置一个标志位
package com.liu.demo03;
public class ThreadStop implements Runnable {
private boolean flag = true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println(">>>线程进行中>>>"+i++ );
}
}
//自己设置一个标志位,用于线程停止
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
ThreadStop threadStop = new ThreadStop();
new Thread(threadStop).start();
for (int i = 0; i < 500; i++) {
System.out.println("主线程"+i);
if(i==200){
threadStop.stop();
System.out.println("线程该停止了");
}
}
}
}
线程休眠:模拟倒计时
package com.liu.demo03;
//线程延时:模拟倒计时
public class ThreadSleep implements Runnable{
@Override
public void run() {
for (int i = 10; i > 0; i--) {
System.out.println("*"+i+"*");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadSleep threadSleep = new ThreadSleep();
Thread thread = new Thread(threadSleep);
System.out.println("开始倒计时");
thread.start();
}
}
/*
*10*
*9*
*8*
*7*
*6*
*5*
*4*
*3*
*2*
*1*
*/
线程礼让
package com.liu.demo03;
//线程礼让
public class ThreadYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始了");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"结束了");
}
public static void main(String[] args) {
ThreadYield threadYield = new ThreadYield();
Thread t1=new Thread(threadYield,"a");
Thread t2=new Thread(threadYield,"b");
t1.start();
t2.start();
}
}
强制执行(插队)
package com.liu.demo03;
//线程礼让
public class ThreadJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 300; i++) {
System.out.println("老子VIP来了!!!办理业务"+i);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadJoin threadJoin = new ThreadJoin();
Thread thread = new Thread(threadJoin);
thread.start();
for (int i = 0; i < 150; i++) {
System.out.println("排队中"+i);
if (i==50){
thread.join();
}
}
}
}
线程优先级
package com.liu.demo03;
//线程优先级
public class ThreadPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程优先级:" +
""+Thread.currentThread().getPriority());//获取优先级
}
public static void main(String[] args) {
System.out.println("默认优先级"+Thread.currentThread().getPriority());
ThreadPriority threadPriority = new ThreadPriority();
//线程优先级最低不能低于1,最高不能高于10
Thread t1 = new Thread(threadPriority,"t1");
t1.setPriority(10);
Thread t2 = new Thread(threadPriority,"t2");
t2.setPriority(1);
Thread t3 = new Thread(threadPriority,"t3");
t3.setPriority(4);
Thread t4 = new Thread(threadPriority,"t4");
t4.setPriority(8);
Thread t5 = new Thread(threadPriority,"t5");
t5.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
/*
默认优先级5
t1线程优先级:10
t2线程优先级:1
t4线程优先级:8
t3线程优先级:4
t5线程优先级:10
*/