一、线程创建
1、直接创建,需要实现Runnable()接口
Thread thread1 =new Thread(new Runnable() {
       @Override
                        public void run() {
Log.i("test","线程执行");
}
2、创建一个类,继承Thread
  (1)、 public class ThreadTest extends Thread {
    @Override
    public void run() {
      super.run();
      try{  
       System.out.println("线程执行代码");
               } catch (InterruptedException e) {
                               e.printStackTrace();
                    }
              }
      (2)、需要使用时,实例化
         ThreadTest t1=new ThreadTest();
    t1.start();
3、特殊线程;创建一个定时器Timer。这个java断承Thread的类
  public class HellowWorld {
      public static void main(String[] args) throws InterruptedException {
            NewtimerTask timerTask=new NewtimerTask();
            Timer timer=new Timer();
            timer.scheduleAtFixedRate(timerTask,new Date(),2000);
      }
      public static class NewtimerTask extends TimerTask {
            @Override
            public void run() {
                  int i = 0;
                  System.out.println("任务开始");
                  while (i < 5) {
                        i++;
                        System.out.println("我是t1计算任务,结果等:" + i);
                  }
                  i=0;
                  System.out.println("任务结束");
            }
      }
}
二、线程控制
     
t1.wait();//(暂停执行)让线程从运行态转换为阻塞态,同时还会释放线程的同步锁。
//wait()方法执行后,t1进入等待状态,直到另一个线程调用此对象的notify()方法或notifyAll()方法,直到它可以重新获得监视器的所有权并恢复执行
下面测试,没有调用notify()时,t1暂停后无法取得执行权
public class HellowWorld {
final static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
try {
System.out.println("线程1开始运行");
object.wait();
System.out.println("线程1结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object) {
System.out.println("线程2开始运行");
try {
Thread.sleep(100);//保证t2没有结束前t1开始运行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2结束");
//object.notify();
}
}
});
t2.start();//开启线程2
t1.start();//开启线程1
}
}
//=======系统打印===========
线程1开始运行
线程2开始运行
线程2结束
----------------------------------------------------------------------
当t2中执行唤醒 object.notify();
//=======系统打印==========
线程1开始运行
线程2开始运行
线程2结束
线程1结束
t1.sleep(1000);//线程休眠(暂停执行)进入阻塞状态,会让线程交出CPU的执行权,下次事件循环需要竞争CPU的执行权
t1.yield();//(暂停执行)不会进入阻塞状态,而是进入可运行态,下次事件直接取到执行权
t1.join();//使该线程先执行完, 其他线程才可以执行
测试t1.join(),t1先执行,但是直到t2完成后,t1才结束
public class HellowWorld {
final static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程1开始运行");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1结束");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程2开始运行");
System.out.println("线程2结束");
}
});
t1.start();//开启线程1
t2.start();//开启线程2
t1.join();
}
}
//===========扫印输出=============
线程1开始运行
线程2开始运行
线程2结束
线程1结束
t1.interrupt();//中断线程,假如当前是在阻塞(sleep,wait,join)时间片中时,会抛出异常并把中断状态改成false
为了使用中断有效,网上介绍使用;两阶段中止模式;
就是在catch (InterruptedException e) {}中再次设置Thread.currentThread().interrupt()中断;
从而保证中断时会执行中断代码;
t1.isInterrupted();//
三、线程任务
(1)、任务只是一段代码,那么实现了Runnabel的类的,都可以称为任务
public class HellowWorld {
    final static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new NewTask());
        t1.start();//开启线程1
    }
    public static class NewTask implements Runnable{
        @Override
        public void run() {
            int i=0;
            while (i<10) {
                i++;
                System.out.println("我是一个计算任务,结果等:" + i);
            }
        }
    }
}
(2)、每个线程指定一个任务,执行顺序由操作系统
public class HellowWorld {
    final static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new NewTask());
        t1.start();//开启线程1
        Thread t2 = new Thread(new NewTask2());
        t2.start();//开启线程1
    }
    public static class NewTask implements Runnable{
        @Override
        public void run() {
            int i=0;
            while (i<10) {
                i++;
                System.out.println("我是t1计算任务,结果等:" + i);
            }
        }
    }
    public static class NewTask2 implements Runnable{
        @Override
        public void run() {
            int i=0;
            while (i<10) {
                i++;
                System.out.println("我是t2计算任务,结果等:" + i);
            }
        }
    }
}
//========打印结果=============
我是t2计算任务,结果等:1
我是t1计算任务,结果等:1
我是t2计算任务,结果等:2
我是t1计算任务,结果等:2
我是t1计算任务,结果等:3
我是t1计算任务,结果等:4
我是t1计算任务,结果等:5
我是t1计算任务,结果等:6
我是t1计算任务,结果等:7
我是t1计算任务,结果等:8
我是t1计算任务,结果等:9
我是t1计算任务,结果等:10
我是t2计算任务,结果等:3
我是t2计算任务,结果等:4
我是t2计算任务,结果等:5
我是t2计算任务,结果等:6
我是t2计算任务,结果等:7
我是t2计算任务,结果等:8
我是t2计算任务,结果等:9
我是t2计算任务,结果等:10
3、TimerTask定时任务,这个是java自带的任务,实现了Runnable
4、FutureTask这个任务与别的任务不同之处是可以返回任务执行完成的结果;
public class HellowWorld {
    public static void main(String[] args) throws InterruptedException {
        FutureTask futureTask = new FutureTask(new Taskable());
        Thread t1=new Thread(futureTask);
        t1.start();
        try {
            int backint=(int)futureTask.get();
            System.out.println("任务返回值:"+backint);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    public static class Taskable implements  Callable {
        @Override
        public Object call() throws Exception {
            int i = 1;
            System.out.println("任务开始");
            while (i < 5) {
                i++;
                System.out.println("我是t1计算任务,结果等:" + i);
            }
            return i;
        }
    }
}
//========打印结果=============
任务开始
我是t1计算任务,结果等:2
我是t1计算任务,结果等:3
我是t1计算任务,结果等:4
我是t1计算任务,结果等:5
任务返回值:5
四、线程池
public class  HellowWorld {
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<Runnable> ThreadQueue =new LinkedBlockingQueue<>(5);
        ExecutorService executor = new ThreadPoolExecutor(1, 5, 100, TimeUnit.MILLISECONDS, ThreadQueue);
        executor.execute(new Task(0));
        //创建多任务
        for (int i = 1; i < 10; i++) {
            ThreadQueue.put(new Task(i));
            System.out.println("队列"+i+"开始执行");
        }
    }
    private static class Task implements Runnable{
        int result;
        public Task(int i) {
            this.result=i;
        }
        @Override
        public void run() {
            System.out.println("任务"+result+"开始执行");
            System.out.println("任务运行中...");
        }
    }
}
原文:https://www.cnblogs.com/popsn/p/13128500.html