1个回答
展开全部
4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。
参考一下以下程序吧::
package com.lzy.interviewing;
public class ThreadTest1 {
private int j ;
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "This +j is :"
+ j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "This -j is :"
+ j);
}
class Inc implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
inc();
}
}
}
class Dec implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
dec();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest1 tTest = new ThreadTest1();
Inc inc = tTest.new Inc();
Dec dec = tTest.new Dec();
for (int i = 0; i < 2; i++) {
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
}
参考一下以下程序吧::
package com.lzy.interviewing;
public class ThreadTest1 {
private int j ;
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "This +j is :"
+ j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "This -j is :"
+ j);
}
class Inc implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
inc();
}
}
}
class Dec implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
dec();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest1 tTest = new ThreadTest1();
Inc inc = tTest.new Inc();
Dec dec = tTest.new Dec();
for (int i = 0; i < 2; i++) {
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询