java结束全部操作代码_Java基本的线程操作(附代码)

啦啦啦啦,从头整理一遍java并发的内容.开始是基本的线程操作

线程状态切换:

ed086021824fc893ddd7ce5bc6114257.png

新建线程:

@Testpublic voidnewTread(){

Thread t1= new Thread(newRunnable() {

@Overridepublic voidrun() {

System.out.println("ok...");

}

});

t1.start();

}

终止线程:

Thread.stop() 不推荐使用。它会释放所有monitor

中断线程:

public void Thread.interrupt() // 中断线程

public boolean Thread.isInterrupted() // 判断是否被中断

public static boolean Thread.interrupted() // 判断是否被中断,并清除当前中断状态

public voidrun(){while(true){if(Thread.currentThread().isInterrupted()){

System.out.println("Interruted!");break;

}

Thread.yield();

}

}

t1.start();

t1.interrupt();

sleep:

public static native void sleep(long millis) throws InterruptedException

public voidrun(){while(true){if(Thread.currentThread().isInterrupted()){

System.out.println("Interruted!");break;

}try{

Thread.sleep(2000);

}catch(InterruptedException e) {

System.out.println("Interruted When Sleep");//设置中断状态,抛出异常后会清除中断标记位

Thread.currentThread().interrupt();

}

Thread.yield();

}

}

挂起 and 继续执行:

– suspend()不会释放锁

– 如果加锁发生在resume()之前 ,则死锁发生

679f7a8ce47f108d851f8fe57dc3361d.png

等待线程结束(join)和谦让(yeild)

public final void join() throws InterruptedException

public final synchronized void join(long millis) throws InterruptedException

join的本质

while (isAlive()) {

wait(0);

}

线程执行完毕后,系统会调用notifyAll();

public classJoinMain {public volatile static int i=0;public static class AddThread extendsThread{

@Overridepublic voidrun() {for(i=0;i<10000000;i++);

}

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

AddThread at=newAddThread();

at.start();

at.join();

System.out.println(i);

}

}

synchronized

– 指定加锁对象:对给定对象加锁,进入同步代码前要获得给定对象的锁。

– 直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。

– 直接作用于静态方法:相当于对当前类加锁,进入同步代码前要获得当前类的锁。

   Object.wait() Obejct.notify()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值