启动四个线程运行
class TestThread { public static void main(String[] args) { Data data = new Data(); //创建四个线程 Thread thadd1 = new ThreadAdd(data, "thadd1"); Thread thadd2 = new ThreadAdd(data, "thadd2"); Thread thsub1 = new ThreadSub(data, "thsub1"); Thread thsub2 = new ThreadSub(data, "thsub2"); //启动四个线程 thadd1.start(); thadd2.start(); thsub1.start(); thsub2.start(); } }
编译,运行以及输出的结果为:
例2 通过join()方法中断一个线程
需要修改上例的代码(只修改main()方法):
class TestThread { public static void main(String[] args) { Data data = new Data(); //创建四个线程 Thread thadd1 = new ThreadAdd(data, "thadd1"); Thread thadd2 = new ThreadAdd(data, "thadd2"); Thread thsub1 = new ThreadSub(data, "thsub1"); Thread thsub2 = new ThreadSub(data, "thsub2"); //启动四个线程 thadd1.start(); try { thadd1.join(); //thadd1执行完后才输出“join() 已经执行完毕” } catch (Exception e) { e.printStackTrace(); } System.out.println("join() 已经执行完毕"); thadd2.start(); thsub1.start(); thsub2.start(); } }
运行的结果如图4:
http://www.5itjob.com
http://www.rjpx.net