1.两个线程交替打印

package Mult_thread;

public class turnPrint {
    private volatile int flag = 0;
    private volatile int count = 1;
    public static void main(String[] args) {
        turnPrint t = new turnPrint();
        t.getThread();
    }
    public void getThread(){
        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thread2());
        t1.start();
        t2.start();
    }
    public class Thread1 implements Runnable{
        public void run(){
            while(count<=100){
                if(flag==0){
                    System.out.println(count);
                    count++;
                    flag = 1;
                }
            }
        }
    }
    public class Thread2 implements Runnable{
        public void run(){
            while(count<=100){
                if(flag==1){
                    System.out.println(count);
                    count++;
                    flag = 0;
                }
            }
        }


    }
}
public class Main {
    volatile int flag=0;
    public static void main(String[] args) throws InterruptedException {
        Main thread = new Main();
        thread.runThread();
    }
    public void runThread() throws InterruptedException{
        Thread t1=new Thread(new Thread1());
        Thread t2=new Thread(new Thread2());
        t1.start();
        t2.start();
    }
    public class Thread1 implements Runnable{
        public void run() {
            int i=1;
            while(i<=99){
                if(flag==0)
                {
                    System.out.println("t1="+i+"flag="+flag);
                    i+=2;
                    flag=1;
                }
            }
        }
    }
    public class Thread2 implements Runnable{

        public void run() {
            int i=2;
            while(i<=100){
                if(flag==1)
                {
                    System.out.println("t2="+i+"flag="+flag);
                    i+=2;
                    flag=0;
                }
            }
        }
    }
}
View Code

相关文章: