最常见的面试机题,涉及四个线程,两个对j加一,两个对j减一。
这个题太常见了,但是要自己独立的默写出来也不是很容易的哦!
代码:
package renrenPratice;public class testSomeThread {/** * @param args */int j = 10;public static void main(String[] args) {// TODO Auto-generated method stubtestSomeThread tt = new testSomeThread();addJ myaddj = tt.new addJ();minusJ myminusj = tt.new minusJ();for (int m = 0; m < 2; m++) {Thread t = new Thread(myaddj);t.start();t = new Thread(myminusj);t.start();}}private synchronized void addj() {// TODO Auto-generated method stubfor (int k = 0; k < 10; k++) {++j;System.out.println("j++ --> now j is " + j);}}private synchronized void minusj() {// TODO Auto-generated method stubfor (int l = 0; l < 10; l++) {--j;System.out.println("j-- --> now j is " + j);}}class addJ implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubaddj();}}class minusJ implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubminusj();}}}
j++ --> now j is 11j++ --> now j is 12j++ --> now j is 13j++ --> now j is 14j++ --> now j is 15j++ --> now j is 16j++ --> now j is 17j++ --> now j is 18j++ --> now j is 19j++ --> now j is 20j-- --> now j is 19j-- --> now j is 18j-- --> now j is 17j-- --> now j is 16j-- --> now j is 15j-- --> now j is 14j-- --> now j is 13j-- --> now j is 12j-- --> now j is 11j-- --> now j is 10j++ --> now j is 11j++ --> now j is 12j++ --> now j is 13j++ --> now j is 14j++ --> now j is 15j++ --> now j is 16j++ --> now j is 17j++ --> now j is 18j++ --> now j is 19j++ --> now j is 20j-- --> now j is 19j-- --> now j is 18j-- --> now j is 17j-- --> now j is 16j-- --> now j is 15j-- --> now j is 14j-- --> now j is 13j-- --> now j is 12j-- --> now j is 11j-- --> now j is 10