前面的忘得差不多了,搞了很久才搞出来,代码如下
- package cn.itheima.bbs.problem;
- public class ThreadDemo {
- public static void main(String[] args) {
- Sum s = new Sum();
- /*AddThread at0 = new AddThread(1,s);
- AddThread at1 = new AddThread(11,s);
- AddThread at2 = new AddThread(21,s);
- AddThread at3 = new AddThread(31,s);
- AddThread at4 = new AddThread(41,s);
- AddThread at5 = new AddThread(51,s);
- AddThread at6 = new AddThread(61,s);
- AddThread at7 = new AddThread(71,s);
- AddThread at8 = new AddThread(81,s);
- AddThread at9 = new AddThread(91,s);
- Thread t0 = new Thread(at0);
- Thread t1 = new Thread(at1);
- Thread t2 = new Thread(at2);
- Thread t3 = new Thread(at3);
- Thread t4 = new Thread(at4);
- Thread t5 = new Thread(at5);
- Thread t6 = new Thread(at6);
- Thread t7 = new Thread(at7);
- Thread t8 = new Thread(at8);
- Thread t9 = new Thread(at9);*/
- for(int i = 0; i<10;i++){
- new Thread(new AddThread(i*10+1,s)).start();
- }
- /*t0.start();
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- t6.start();
- t7.start();
- t8.start();
- t9.start();*/
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(Sum.sum);
- }
- }
- class AddThread implements Runnable {
- int a;
- Sum s ;
- AddThread(int a,Sum s) {
- this.a = a;
- this.s = s;
- }
- @Override
- public void run() {
- synchronized(s){
- for (int j = 0; j < 10; j++) {
- Sum.sum = Sum.sum + j + a;
- System.out.println(Thread.currentThread().getName()+"is running!");
- }
- }
- }
- }
- class Sum{
- public static int sum = 0;
- }
复制代码 |