线程的创建

基本线程类:

Thread

 MyThread my = new MyThread();
  my.start();
 1  //当前线程可转让cpu控制权,让别的就绪状态线程运行(切换)
 2  public static Thread.yield() 
 3  //暂停一段时间
 4  public static Thread.sleep()  
 5  //在一个线程中调用other.join(),将等待other执行完后才继续本线程。    
 6  public join()
 7  //中断线程->
 8 //终端只会影响到wait状态、sleep状态和join状态。被打断的线程会抛出InterruptedException。
 9 //正常线程不会去检测  不受影响
10  public interrupte()

Runnable

 1 public class MyRunnable implements Runnable{
 2     @Override
 3     public void run() {
 4             System.out.println("my runnable  running !");
 5     }
 6     public static void main(String[] args) {
 7         Runnable myRunable = new MyRunnable();
 8         Thread myThread = new Thread(myRunable);
 9         myThread.start();        
10     }
11 }

 

Callable ,  Future

  FutureTask  实现了 future接口和runnable接口

 1 public class MyCallable implements Callable<Integer>{
 2     @Override
 3     public Integer call() throws Exception {
 4         Integer i = new Random().nextInt();
 5         return i;
 6     }
 7     public static void main(String[] args) {
 8         //创建 callable
 9         MyCallable myCallable = new MyCallable();
10         //可以接收 callable  的返回值   判断线程终止
11         FutureTask<Integer> future = new FutureTask(myCallable);
12         //开启线程
13         new Thread(future).start();        
14     }
15 }

 

posted @ 2018-03-24 10:33  千彧  阅读(131)  评论(0编辑  收藏  举报