8 多线程 - shuzi323/java-study GitHub Wiki

  • 任务类必须实现Runnable接口,它只包含一个run方法。
Runnable printA = new PrintChar('a', 100);  //PrintChar类实现run()方法
Thread thread1 = new Thread(printA);
thread1.start();
  • 在run()方法中,可以使用Thread.yield()为其他线程临时让出CPU时间;如果用ThreadSleep(t)或threadX.join()(等待threadX完成),需要try catch InterruptedException异常,循环需要放在try中。
  • 线程池:
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.execute(new PrintNum(100));
executor.execute(new PrintChar('a', 100));
executor.execute(new PrintChar('b', 100));
executor.shutdown();                //executor.isTerminated()  如果线程池中所有任务都被终止,返货true
  • Synchronized 关键字:给同步方法加锁,对实例方法,要给调用该方法的对象加锁;对静态方法,要给这个类加锁;也可以给代码块加锁