Java--多线程:一个变量初始值100,一个任务对它进行50次自增操作,而另外一个任务对它进行50次自减操作。
题目:一个变量初始值100,一个任务对它进行50次自增操作,而另外一个任务对它进行50次自减操作。
思路:将操作的共同数据,同步锁,共同方法放到同一个类中,再由线程调用这个类对象.
代码:
public class Day61 {
public static void main ( String [ ] args) {
int n = 50 , m = 50 ;
int num = 100 ;
new Day61 ( ) . init ( num, n, m) ;
}
public void init ( final int num, final int n, final int m) {
final PrintNum printNum = new PrintNum ( num) ;
new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
printNum. print ( "最终值" ) ;
}
} ) . start ( ) ;
new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < m; i++ ) {
printNum. minus ( ) ;
}
printNum. changePrintFlag ( ) ;
}
} ) . start ( ) ;
new Thread ( new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < n; i++ ) {
printNum. add ( ) ;
}
printNum. changeOptionFlag ( ) ;
}
} ) . start ( ) ;
}
}
class PrintNum {
private boolean printFlag = false ;
private boolean optionFlag = true ;
int num1;
public PrintNum ( int num) {
num1 = num;
}
public synchronized void print ( String str) {
while ( ! printFlag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System . out. println ( str + num1) ;
this . notify ( ) ;
printFlag = ! printFlag;
}
public synchronized void add ( ) {
while ( ! optionFlag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
num1++ ;
System . out. println ( "自加:" + num1) ;
this . notify ( ) ;
}
public synchronized void minus ( ) {
while ( optionFlag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
num1-- ;
System . out. println ( "自减:" + num1) ;
this . notify ( ) ;
}
public void changePrintFlag ( ) {
printFlag = ! printFlag;
}
public void changeOptionFlag ( ) {
optionFlag = ! optionFlag;
}
}