java线程面试手写题

java

1.设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

 1 public class Question1 {

2

3 private int j = 0;

4 /**

5 * @param args

6 */

7 public static void main(String[] args) {

8 Question1 q = new Question1();

9 Dec dec = q.new Dec();

10 Inc inc = q.new Inc();

11 for(int i=0; i<2;i++){

12 Thread t2 = new Thread(inc);

13 t2.start();

14 Thread t1 = new Thread(dec);

15 t1.start();

16

17 }

18 }

19

20 private synchronized void inc(){

21 j++;

22 System.out.println( Thread.currentThread().getName()+"-inc:"+j);

23 }

24

25 private synchronized void dec(){

26 j--;

27 System.out.println( Thread.currentThread().getName()+"-dec:"+j);

28 }

29 class Inc implements Runnable {

30

31 @Override

32 public void run() {

33 inc();

34

35 }

36 }

37

38 class Dec implements Runnable {

39

40 @Override

41 public void run() {

42 dec();

43

44 }

45

46 }

47 }

2.设计4个线程, 其中3个线程将一个长度为3的数组每项增加1,第4个线程输出数组3个数的和写出程序。

public class Question2 {

int[] a = new int[3];

/**

* @param args

*/

public static void main(String[] args) {

Question2 q = new Question2();

Inc inc = q.new Inc();

Print p = q.new Print();

for(int i=0; i<3; i++){

Thread t1 = new Thread(inc);

t1.start();

}

Thread t2 = new Thread(p);

t2.start();

}

private synchronized void inc(){

for(int i=0;i<a.length;i++){

a[i] += 1;

}

System.out.println(Thread.currentThread().getName()+"-inc:"+Arrays.toString(a));

}

private synchronized void print(){

int sum = 0;

for(int i=0;i<a.length;i++){

sum += a[i];

}

System.out.println(Thread.currentThread().getName()+"-print:"+Arrays.toString(a)+"和为:"+sum);

}

class Inc implements Runnable {

@Override

public void run() {

inc();

}

}

class Print implements Runnable {

@Override

public void run() {

print();

}

}

}

以上是 java线程面试手写题 的全部内容, 来源链接: utcz.com/z/390929.html

回到顶部