2019329621175-张子行homework-5 Version 0 |
|
👤 Author: by 1148873699qqcom 2021-12-19 07:39:59 |
If each thread executes a different code, assuming there are two different threads, two Runnables are needed to implement this.
Use the internal class method, write the shared data in the internal class, provide different methods for each thread (remember to add locks), then create instances and pass them as parameters to each Runnable constructor, and share data and call different methods through the object passed by the constructor.
public class multithreads {
public static void main(String[] args) {
Data data = new Data();
Runnbale1 runnbale1 = new Runnbale1(data);
Runnbale2 runnbale2 = new Runnbale2(data);
new Thread(runnbale1).start();
new Thread(runnbale2).start();
}
private static class Runnbale1 implements Runnable {
private Data data;
public Runnbale1(Data data) {
this.data = data;
}
@Override
public void run() {
int plus = data.plus();
System.out.println(Thread.currentThread().getName() + "---" + plus);
}
}
private static class Runnbale2 implements Runnable {
private Data data;
public Runnbale2(Data data) {
this.data = data;
}
@Override
public void run() {
int reduce = data.reduce();
System.out.println(Thread.currentThread().getName() + "---" + reduce);
}
}
private static class Data {
private int i = 100;
public synchronized int plus(){
return i++;
}
public synchronized int reduce(){
return i--;
}
}
}