快捷搜索:

多线程小案例

package com.njbdqn;

import jdk.management.resource.internal.inst.InitInstrumentation;

import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

public class ThreadDemo { static int[] arr = new int[10]; static int i=0;

static void cal1(int ix){ int sum = 0; for (int i = ix*10+1; i <=(ix+1)*10; i++) { sum += i; } arr[ix] = sum; i++; System.out.println(Thread.currentThread().getName()+":"+sum); }

static int cal3(int ix){ int sum = 0; for (int i = 0; i < 100; i+=10) { sum += i+ix+1; System.out.println(Thread.currentThread().getName()+":"+sum); } return sum; }

static void cal2(int ix){ int sum = 0; for (int i = 0; i < 100; i+=10) { sum += i+ix+1; System.out.println(Thread.currentThread().getName()+":"+sum); } arr[ix] = sum; i++;

}

static class Sum implements Runnable{ private int ix; public Sum(int ix){ this.ix =ix; } @Override public void run() { cal2(ix); } }

public static void main(String[] args) throws InterruptedException, ExecutionException { //方法一 // Thread[] ths = new Thread[10]; // for (int i = 0; i < ths.length; i++) { // ths[i] = new Thread(new Sum(i)); // ths[i].start(); ths[i].join(); //等到这条线程死亡 // } // while(i<10){ // Thread.sleep(1000); // }

//方法二 ExecutorService service = Executors.newFixedThreadPool(10); //顺序执行 // for (int j = 0; j < arr.length; j++) { // final int _j=j; // arr[j] = service.submit(new Callable<Integer>() { // @Override // public Integer call() throws Exception { // return cal3(_j); // } // }).get(); // }

//并发执行 for (int j = 0; j < arr.length; j++) { service.submit(new Sum(j)); }

while(i<10){ Thread.sleep(200); }

int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } System.out.println("sum all : "+sum);

// new Thread(){ // @Override // public void run() { // super.run(); // } // }.start();

}

}

public class MyThread exends Thread{ private static Integer count=0; public void run(){ while(true){ synconized(count) { int flag = Integer.parseInt(Thread.currentThread().getName().split("-")[1]); if(flag%2==0){ count++; }else{ count--; } } } }

public static void main(String [] args){ for (int i=0;i<4;i++) { new MyThread().start() } } }

public class MyThread implements Runable{ private int count=0; public void run() { while(true){ int flag = Integer.parseInt(Thread.currentThread().getName().split("-")[1]); if(flag%2==0){ add(); }else{ sub(); } } } public synconized void add(){ count++; } public synconized void sub(){ count--; } public static void main(String [] args){ MyThread mt1 = new MyThread(); for (int i=0;i<4;i++) { new Thread(mt1).start(); } } }

经验分享 程序员 微信小程序 职场和发展