多线程2

来源:互联网 发布:swift完整项目源码 编辑:程序博客网 时间:2024/05/16 02:14

1. wait()和sleep()的区别?

sleep():必须指定时间,不释放锁

wait():  可以指定时间,也可以不指定;释放锁

2. 为什么wait()、notify()、notifyAll()方法必须定义在Object中?

因为这些方法的调用是依赖于锁对象的,而同步代码块的锁对象是任意对象,所以定义在Object类中。

3. 线程池;

使用Runnable子类对象作为submit方法的参数

/* * 线程池的使用: * A:创建一个线程池对象,控制要创建几个线程池对象 *  * B:这种线程池的对象可以执行Runnable对象或Callable对象代表的线程 * C:调用如下方法: * <T> Future<T> submit(Callable<T> task)  提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future。  * Future<?> submit(Runnable task) 提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。  * D:结束: *  void shutdown() 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。  */public class ExecutorsDemo {public static void main(String[] args) {//创建一个线程池对象,控制要创建几个线程对象//public static ExecutorService newFixedThreadPool(int nThreads)ExecutorService es = Executors.newFixedThreadPool(2);//RunnableDemo是实现了Runnable接口的类es.submit(new RunnableDemo());es.submit(new RunnableDemo());//结束线程池es.shutdown();}}

使用Callable子类对象作为submit方法的参数

public class ExecutorsDemo1 {public static void main(String[] args) throws InterruptedException, ExecutionException {// 创建线程池对象,同时规定创建两个线程ExecutorService es = Executors.newFixedThreadPool(2);// <T> Future<T> submit(Callable<T> task)Future<Integer> f = es.submit(new MyCallable(100));Future<Integer> ff = es.submit(new MyCallable(50));// V get() 如有必要,等待计算完成,然后获取其结果。 V即为对应的泛型Integer sum1 = f.get();Integer sum2 = ff.get();System.out.println(sum1+"---"+sum2);//关闭线程es.shutdown();}}class MyCallable implements Callable<Integer> {private int number;public MyCallable(int number) {this.number = number;}//带返回值,加泛型//这里实现一个求和案例@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 1; i <= number; i++) {sum += i;}return sum;}}

4. 计时器的应用:
import java.util.Timer;import java.util.TimerTask;/* * 定时器:可以让我们在指定的时间内做某件事情,还可以重复的做某件事情 * 依赖Timer和TimerTask这两个类 * Timer: * Timer()  创建一个新计时器。 * void schedule(TimerTask task, long delay) 安排在指定延迟后执行指定的任务。  * void schedule(TimerTask task, long delay, long period)  安排指定的任务从指定的延迟后开始进行重复的固定延迟执行。  * void schedule(TimerTask task, Date firstTime, long period) 安排指定的任务在指定的时间开始进行重复的固定延迟执行。 * void cancel()  终止此计时器,丢弃所有当前已安排的任务。   * TimerTask:  由 Timer 安排为一次执行或重复执行的任务。  */public class TimerDemo {public static void main(String[] args) {Timer t = new Timer();// 在三秒后执行任务 t.schedule(new Mytask(t), 3000);// 在三秒后执行任务,并在两秒延迟后重复执行,后面的参数为毫秒值//t.schedule(new Mytask(), 3000, 2000);}}class Mytask extends TimerTask {private Timer t;// 无参构造public Mytask() {}// 带参构造,将Timer对象赋值给成员变量,便于调用cancel()方法public Mytask(Timer t) {this.t = t;}@Overridepublic void run() {// 这里写需要被执行的代码System.out.println("好好学习");// 结束任务t.cancel();}}




0 0
原创粉丝点击