设计两个线程, 使一个使J增加1, 另一个减1
public class TestThread implements Runnable {
private int j;public synchronized void increase()
{
j++;
}public synchronized void decrease()
{
j--;
}.....
}帮我设计一下只有一个线程访问increase() 和decrease()
public class TestThread implements Runnable {
private int j;public synchronized void increase()
{
j++;
}public synchronized void decrease()
{
j--;
}.....
}帮我设计一下只有一个线程访问increase() 和decrease()
private int j;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec(); Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start(); }
private synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}
private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+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();
}
}
}
}
private int j;
public synchronized void increase()
{
j++;
} public synchronized void decrease()
{
j--;
}
public void printf(){
System.out.println(j);
}
}
class InThread implements Runnable {
Resoure r;
InThread (Resoure s){
this.r=s;
}
public void run() {
for (int i=0;i<=10;i++){
r.increase();
System.out.print("in InThread ");
r.printf();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class DeThread implements Runnable{
Resoure r;
DeThread (Resoure s){
this.r=s;
}
public void run() {
for (int i=0;i<=10;i++){
r.decrease();
System.out.print("in DeThread ");
r.printf();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class TestThread{
public static void main(String args[]){
Resoure r=new Resoure();
InThread t1=new InThread(r);
DeThread t2 =new DeThread(r);
new Thread(t1).start();
new Thread(t2).start();
}
}
写了下
帮我设计一下只有一个线程访问increase() 和decrease()
也就是说有一个线程在访问increase()时, 就不能有线程访问decrease()了