这是毕老师在视频提的一个例子 用synchronized解决多线程安全问题
他说用单例设计模式也可以 但我试了几回都不对 求大神帮解决
- class Res{
- String name;
- String sex;
- }
- class Input implements Runnable{
- private Res r;
- public Input(Res r){
- this.r = r;
- }
- public void run(){
- int x =0;
- while(true){
- synchronized(r){
- if(x==0){
- r.name = "mike";
- r.sex = "男";
- }else{
- r.name = "lily";
- r.sex = "女";
- }
-
- }
- x = (x+1)%2;
- }
- }
- }
- class Output implements Runnable{
- private Res r;
- public Output(Res r){
- this.r = r;
- }
- public void run(){
- while(true){
- synchronized(r){
- System.out.println(r.name+"---"+r.sex);
- }
- }
- }
- }
- public class InputOutputDemo01 {
- public static void main(String[] args) {
- Res r = new Res();
-
- Input in = new Input(r);
- Output out = new Output(r);
-
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(out);
- t1.start();
- t2.start();
- }
- }
复制代码 |