Java基本的线程操作(附代码)

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

 

线程状态切换:

 

新建线程:

  

@Test
    public void newTread(){
        Thread t1 = new Thread(new Runnable() {
            
            @Override
            public void run() {
                System.out.println("ok...");
            }
        });
        t1.start();
                
    }

 

终止线程:

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

 

中断线程:

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

 

public void run(){
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 void run(){
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()之前 ,则死锁发生

 

 

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

  public final void join() throws InterruptedException
  public final synchronized void join(long millis) throws InterruptedException

  join的本质
  while (isAlive()) {
    wait(0);
  }

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

  

public class JoinMain {
public volatile static int i=0;
public static class AddThread extends Thread{
@Override
public void run() {
for(i=0;i<10000000;i++);
}
}
public static void main(String[] args) throws InterruptedException {
AddThread at=new AddThread();
at.start();
at.join();
System.out.println(i);
}
}

synchronized
  – 指定加锁对象:对给定对象加锁,进入同步代码前要获得给定对象的锁。
  – 直接作用于实例方法:相当于对当前实例加锁,进入同步代码前要获得当前实例的锁。
  – 直接作用于静态方法:相当于对当前类加锁,进入同步代码前要获得当前类的锁。
   Object.wait() Obejct.notify()

 

 

  

posted @ 2016-04-24 10:31  嘟嘟死胖子  阅读(257)  评论(0编辑  收藏  举报