一、创建线程
继承Thread类
public class MyThread extends Thread{
@Override
public void run() {
super.run();
}
public static void main(String[] args) {
Thread th = new MyThread();
th.start();
}
}
实现Runnable接口
public class MyThread implements Runnable{
@Override
public void run() {
}
public static void main(String[] args) {
MyThread mt = new MyThread();
Thread th = new Thread(mt);
th.start();
}
}
Callable和Future(该方法创建的线程可获得返回结果)
public class ThreadTestByCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task=new FutureTask<String>((Callable<String>)()->{
int i=0;
return "12313";
});//第一种方法JAVA8新特性lambda表达式,需要学习。
Thread th = new Thread(task,"1");
th.start();
System.err.println(th.getName()+"-"+task.get());
ThreadTestByCallable demo = new ThreadTestByCallable();
FutureTask<String> task1 = new FutureTask<>(demo.new Task());//第二种方法
Thread th1 = new Thread(task1,"2");
th1.start();
System.err.println(th1.getName()+"-"+task1.get());
}
class Task implements Callable<String>{
@Override
public String call() throws Exception {
return "11111";
}
}
二、方法
run()/call():Thread下start()、.ExecutorService下execute()、submit(),ScheduledExecutorService下scheduleAtFixedRate()所调用的方法
1. execute(Runnable command);将线程加到线程池并执行,无返回结果
2.submit(Runnable command);将线程加到线程池并执行,返回FutureTask<?>对象但是调用.get()方法只能得到null
3.submit(Runnable command,T result);将线程加到线程池并执行,相对于上一个方法可以手动指定线程返回结果,返回FutureTask<?>对象调用.get()方法的时候就会得到指定的result
4.submit(Callable<T> task);将线程加到线程池并执行(call()),返回FutureTask<?>对象调用.get()方法可以得到线程的返回结果
5.scheduleAtFixedRate()也支持,但是和Callable的搭配暂时未测试。
sleep():睡眠,不释放锁,到了时间会继续运行
wait():睡眠,释放锁,到了时间或者被notify()/notifyAll()唤醒后会进入准备状态,而不会立即执行
join():合并线程成串行执行,main()中创建线程A,并且调用A.join()则,执行到这的时候后续main()方法执行的语句就会被 wait(),直到A执行完,或者指定的时间结束(之后恢复普通的并行执行)
yield():暂停线程让优先级高的或者同等的有执行机会。
notify():唤醒wait()中的一个线程,必须针对同一个对象。A.wait();A.notify();synchronized (A) {}
notifyAll():同上不过是唤醒wait()中的所有线程。