Java16-8 线程停止及其他线程方法
2018-11-27 本文已影响0人
第二套广播体操
如何让线程停止?
原理:让run方法结束
线程任务通常都有循环,因为开启线程就是为了需要一些时间的代码
只要控制住循环,就可以结束run方法,以此结束线程
控制循环用标记即可
class StopThread implements Runnable{
private boolean sign=true;
@Override
public synchronized void run() {
while (sign)
{
try {
wait();
}
catch (InterruptedException e){
System.out.println(Thread.currentThread().toString());
}
System.out.println(Thread.currentThread().getName()+"\t"+"程泽琪是猪");
}
}
public void setSign(){
sign=false;
}
}
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread=new StopThread();
Thread t1=new Thread(stopThread);
Thread t2=new Thread(stopThread);
t1.start();//t1 t2进入后等待无法结束 造成死锁
t2.start();
for (int i = 0; i <40; i++) {
if (i==30)
stopThread.setSign();
System.out.println(Thread.currentThread().getName()+"\t"+"程大傻");
}
System.out.println("over");
}
}
同步后造成死锁
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread=new StopThread();
Thread t1=new Thread(stopThread,"线程1");
Thread t2=new Thread(stopThread,"线程2");
t1.start();//t1 t2进入后等待无法结束 造成死锁
t2.start();
for (int i = 0; i <40; i++) {
if (i==30) {
stopThread.setSign();
t1.interrupt();
t2.interrupt();
}
System.out.println(Thread.currentThread().getName()+"\t"+"程大傻");
}
System.out.println("over");
}
}
使用interrupt();方法 中断线程 ,强行激活线程
因为强制激活 所有会抛出InterruptedException异常
setDaemon();方法 守护线程 即会将这个线程标记为后台线程 如果前台线程结束 后台线程也会结束
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread=new StopThread();
Thread t1=new Thread(stopThread,"线程1");
Thread t2=new Thread(stopThread,"线程2");
t1.start();//t1 t2进入后等待无法结束 造成死锁
t2.setDaemon(true);//将t2标记成后台线程
t2.start();
for (int i = 0; i <40; i++) {
if (i==30) {
stopThread.setSign();
t1.interrupt();
// t2.interrupt();
}
System.out.println(Thread.currentThread().getName()+"\t"+"程大傻");
}
System.out.println("over");
}
}
只强制激活t1线程 将t2线程编辑为后台线程 即前台线程(main t1)结束 后台线程(t2)也会结束
join();方法
class JoinTread implements Runnable{
@Override
public void run() {
for (int i = 0; i <140; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+"haha");
}
}
}
public class JoinThreadDemo {
public static void main(String[] args) throws InterruptedException {
JoinTread joinTread=new JoinTread();
Thread t1= new Thread(joinTread,"线程1");
t1.start();
t1.join();//停止该线程中断
new Thread(joinTread,"线程2").start();
for (int i = 0; i <140; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
join();
线程1会都运行完 再交替运行 2线程和主线程
即 主线程会释放权限 让线程1运行完,然后再运行