https://blog.csdn.net/u013760665/article/details/88805644
两个线程交替打印0–1000之间之间的数字(线程1打印偶数,线程2打印奇数),完全可以用synchronized配合wait() notify()的方法实现,但是这样开销比较大。可以采用添加一个flag变量的方法。代码如下:
public class CodeTest {
volatile static int flag=0;//这个flag要被volatile修饰以保证可见性
volatile static int i=0;
public static void main(String[] args) {
Thread t1=new Thread(new Thread1());
Thread t2=new Thread(new Thread2());
t1.start();
t2.start();
}
public static class Thread1 implements Runnable{
public void run() {
// int i=0;
while(i<99){
if(flag==0){
System.out.println("t1="+i);
i++;
flag=1;
}
}
}
}
public static class Thread2 implements Runnable{
public void run(){
// int i=1;
while (i<99){
if(flag==1){
System.out.println("t2="+i);
i++;
flag=0;
}
}
}
}
}
当要求三个线程的时候也可以采用这个方法,但是要注意用volatile关键字保证可见性,代码如下:
public class CodeTest {
volatile static int flag=0;//这个flag要被volatile修饰以保证可见性
private static volatile int i=0;
public static void main(String[] args) {
Thread thread1=new Thread(new Thread1());
Thread thread2=new Thread(new Thread2());
Thread thread3=new Thread(new Thread3());
thread1.start();
thread2.start();
thread3.start();
}
public static class Thread1 implements Runnable{
public void run() {
while(i<100){
if(flag==0) {
System.out.println("t1="+i);
i++;
flag=1;
}
}
}
}
public static class Thread2 implements Runnable{
public void run() {
while(i<100){
if(flag==1){
System.out.println("t2="+i);
i++;
flag=2;
}
}
}
}
public static class Thread3 implements Runnable{
public void run() {
while(i<100){
if(flag==2){
System.out.println("t3="+i);
i++;
flag=0;
}
}
}
}
}