java线程开启不了_java 线程开启 中断

packagecom.ljj.study;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.FutureTask;public classMyThread {private static class ExtendThread extendsThread {

@Overridepublic voidrun() {

System.out.println("ExtendThread running ");

System.out.println("id: " +Thread.currentThread().getId());

}

}private static class RunThread implementsRunnable {public voidrun() {

System.out.println("RunThread running ");

System.out.println("id: " +Thread.currentThread().getId());

}

}private static class CallThread implements Callable{public String call() throwsException {

System.out.println("CallThread running ");

System.out.println("id: " +Thread.currentThread().getId());return "callresult";

}

}public static void main(String[] args) throwsInterruptedException, ExecutionException {

ExtendThread eh= newExtendThread();

Thread th0= newThread(eh);

RunThread rt= newRunThread();

Thread th1= newThread(rt);

CallThread ct= newCallThread();

FutureTask ft = new FutureTask(ct);

Thread th2= newThread(ft);

th0.start();

th1.start();

th2.start();

System.out.println(ft.get());

}

}

RunThread running

id:13CallThread running

id:14ExtendThread running

callresult

id:12

+++++++++++++++ExtendThread running

CallThread running

id:12RunThread running

id:13id:14callresult

多次运行代码中main方法,发现每次打印结果都不一样,印证了相邻的两条语句甚至同一个语句中两个不同的运算符之间,都有可能插入其他线程或进程的动作。

一般使用实现runnable接口(多实现)和callable接口(有返回值)的方法来创建线程

3.线程中断

stop(),resume(),suspend()已不建议使用,stop()会导致线程不会正确释放资源,suspend()容易导致死锁。

java线程是协作式,而非抢占式

调用一个线程的interrupt() 方法中断一个线程,并不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定。

isInterrupted() 判定当前线程是否处于中断状态。

static方法interrupted() 判定当前线程是否处于中断状态,同时中断标志位改为false。

那么如何理解线程是否中断由线程本身决定?

packagecom.ljj.study;public classEndThread {private static class MyEndThread implementsRunnable {public voidrun() {while (true) {

System.out.println(Thread.currentThread().getName()+ " running ");

}

}

}private static class MyEndThread1 implementsRunnable {public voidrun() {while (!Thread.currentThread().isInterrupted()) {

System.out.println(Thread.currentThread().getName()+ " running ");

}

System.out.println(Thread.currentThread().isInterrupted());

}

}public static void main(String[] args) throwsInterruptedException {//MyEndThread met = new MyEndThread();//Thread t0 = new Thread(met);//t0.start();//

//System.out.println("begin ");//t0.interrupt();

MyEndThread1 met1= newMyEndThread1();

Thread t1= newThread(met1);

t1.start();

t1.sleep(30);

System.out.println("begin ");

t1.interrupt();

}

}

t0线程虽然执行了interrupt方法,但是还是一直在打印,t1线程interrupt方法后就停止打印了,通过对比印证了上述所说。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值