/** * 两个线程交替打印1-100之间的数字 */ public class ThreadTest3 { public static void main(String[] args) { Demo04 demo04 = new Demo04(); Thread t1 = new Thread(demo04); Thread t2 = new Thread(demo04); t1.setName("线程一"); t2.setName("线程二"); t1.start(); t2.start(); } } class Demo04 implements Runnable{ private static int i=1; @Override public void run() { while (true){ synchronized (this){ //唤醒所有线程,首次执行时无效果 notifyAll(); if (i<=100){ System.out.println(Thread.currentThread().getName()+":"+i); i++; try { //使当前线程沉睡。可以被notifyAll()和notify()唤醒 wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { break; } } } } }
wait() 与 notify() 和 notifyAll()
这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报
java.lang.IllegalMonitorStateException异常。
Callable接口
相比run()方法,可以有返回值
方法可以抛出异常
支持泛型的返回值
需要借助FutureTask类,比如获取返回结果
Future接口
public class ThreadTest4 { public static void main(String[] args) throws ExecutionException, InterruptedException { Demo05 demo05 = new Demo05(); FutureTask futureTask = new FutureTask(demo05); new Thread(futureTask).start(); Object o = futureTask.get(); System.out.println(o); } } class Demo05 implements Callable{ @Override public Object call() throws Exception { int sum =0; for (int i = 1; i <=100 ; i++) { if (i%2==0){ System.out.println(i); sum+=i; } } return sum; } }
好处:
实现
public class Pool { public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(10); service.execute(new Demo06()); service.shutdown(); } } class Demo06 implements Runnable{ @Override public void run() { for (int i = 1; i <=100 ; i++) { if (i%2==0){ System.out.println(i); } } } }