几道基础的线程题
第一题
子线程循环十次,每次从1加到10,最后在主线程中相加得到结果?
1 public class CallableTest { 2 public static void main(String[] args) { 3 ThreadDemo demo = new ThreadDemo(); 4 5 FutureTask<Integer> result = new FutureTask<Integer>(demo); 6 7 int sum = 0; 8 for(int i = 0;i < 10;i++){ 9 Thread thread = new Thread(result); 10 thread.start(); 11 try { 12 Integer num = result.get(); 13 sum += num; 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } catch (ExecutionException e) { 17 e.printStackTrace(); 18 } 19 } 20 21 System.out.println(sum); 22 } 23 24 } 25 26 class ThreadDemo implements Callable<Integer> { 27 @Override 28 public Integer call() throws Exception { 29 int sum = 0; 30 for(int i = 1;i <= 10;i++){ 31 sum += i; 32 } 33 return sum; 34 } 35 }
第二题
设计 4 个线程,其中两个线程每次对 j 增加 1,另外两个线程对 j 每次减少
1。写出程序。
1 public class AddSubThread { 2 public static void main(String[] args) { 3 Operater operater = new Operater(); 4 ThreadDemoAdd add = new ThreadDemoAdd(operater); 5 ThreadDemoSub sub = new ThreadDemoSub(operater); 6 7 while(true) { 8 for(int i = 0;i < 2;i++){ 9 new Thread(add).start(); 10 } 11 12 for(int i = 0;i < 2;i++){ 13 new Thread(sub).start(); 14 } 15 } 16 } 17 } 18 19 class ThreadDemoAdd implements Runnable{ 20 private Operater operater; 21 22 public ThreadDemoAdd(Operater operater){ 23 this.operater = operater; 24 } 25 26 @Override 27 public void run() { 28 operater.add(); 29 } 30 31 } 32 33 class ThreadDemoSub implements Runnable { 34 private Operater operater; 35 36 public ThreadDemoSub(Operater operater){ 37 this.operater = operater; 38 } 39 40 @Override 41 public void run() { 42 operater.sub(); 43 } 44 45 } 46 47 class Operater { 48 private int i = 0; 49 50 public synchronized void add(){ 51 i++; 52 System.out.println("i :" + i); 53 } 54 55 public synchronized void sub(){ 56 i--; 57 System.out.println("i :" + i); 58 } 59 }