多线程
import java.io.IOException; import java.util.Set; public class ProcessBuilderDemo { public static void main(String[] args) { final Person p=new Person(); Thread thread=new Thread() { boolean flag=false; public void run() { while (true) { if (flag==false) { p.name="张三"; p.sex="女"; flag=true; } else { p.name="李四"; p.sex="男"; flag=false; } } } }; Runnable runnable=new Runnable() { public void run() { while (true) { System.out.println(p.name+""+p.sex); } } }; thread.start(); new Thread(runnable).start(); } } class Person { String name="1"; String sex="1"; }
以上代码线程不是安全的,所以会出现交替打印
public class ProcessBuilderDemo { public static void main(String[] args) { final Person p = new Person(); Thread thread = new Thread() { boolean flag = false; public void run() { while (true) { if (flag == false) { p.SetNameAndSex("张三","男"); flag = true; } else { p.SetNameAndSex("李四","女"); flag = false; } } } }; Runnable runnable = new Runnable() { public void run() { while (true) { p.GetNameAndSex(); } } }; thread.start(); new Thread(runnable).start(); } } class Person { String name = "1"; String sex = "1"; public void setName(String name) { this.name=name; } public String getName() { return this.name; } public void setSex(String sex) { this.sex=sex; } public String getSex() { return this.sex; } public synchronized void SetNameAndSex(String name,String sex) { this.name=name; this.sex=sex; } public synchronized void GetNameAndSex() { System.out.println(this.name+"---"+this.sex); } }