Java 用两个线程编写一个交替打印的程序

Java 用两个线程编写一个交替打印的程序,java,multithreading,concurrency,Java,Multithreading,Concurrency,我最近在一次采访中被问到这个问题 用两个线程(a和B)编写一个程序,其中a打印1,B打印2,依此类推,直到达到50 我们怎么做呢?这是另一个解决方案: Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { for (int i = 1; i <= 50; i +=

我最近在一次采访中被问到这个问题

用两个线程(a和B)编写一个程序,其中a打印1,B打印2,依此类推,直到达到50


我们怎么做呢?

这是另一个解决方案:

     Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 1; i <= 50; i += 2) {
                    System.out.println("T1=" + i);

                    t1turn = false;
                        try {
                            lock.notifyAll();
                            lock.wait();
                        } catch (InterruptedException e) {
                        }
                }
            }

        }
    });
    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 2; i <= 50; i += 2) {
                    if (t1turn)
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                        }
                    System.out.println("T2=" + i);
                    t1turn = true;
                    lock.notify();
                }
            }
        }
    });
    t1.start();
    t2.start();
Thread t1=新线程(new Runnable(){
@凌驾
公开募捐{
已同步(锁定){

对于(int i=1;i可能是),这仍然是相关的:

public class MyRunnable implements Runnable {
    public static int counter = 0;
    public static int turn = 0;
    public static Object lock = new Object();

    @Override
    public void run() {
        while (counter < 50) {
            synchronized (lock) {
                if (turn == 0) {

                    System.out.println(counter + " from thread "
                            + Thread.currentThread().getName());
                    turn = 1;
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                } else {
                    turn = 0;
                    lock.notify();
                }

            }
        }
    }
}

}

赋值的本质是演示一个线程如何向另一个线程发送信号。最常见的方法是使用阻塞队列,但在这里,信号不携带任何信息,因此信号量就足够了

创建线程类,该类由2个信号量参数化:输入和输出:

class ThreadPrinter implements Runnable {
    int counter;
    Semaphore ins, outs;

    ThreadPrinter(int counter, Semaphore ins, Semaphore outs) {
        this.counter = counter;
        this.ins = ins;
        this.outs = outs;
    }

    @Override
    public void run() {
        for (int i = 0; i < 25; i++) {
            ins.aquire(); // wait for permission to run
            System.out.println("" + counter);
            outs.release();  // allow another thread to run
            counter += 2;
        }
    }
注意信号量
a
b
按不同顺序通过。

公共类测试{
public class Test {

private static int count = 0;

public static void main(String[] args) throws InterruptedException {

    Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {

            for (int i = 0; i < 25; i++) {
                synchronized (CommonUtil.mLock) {
                    incrementCount();
                    CommonUtil.mLock.notify();
                    try {
                        CommonUtil.mLock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {

            for (int i = 0; i < 25; i++) {
                synchronized (CommonUtil.mLock) {
                    incrementCount();
                    CommonUtil.mLock.notify();
                    try {
                        CommonUtil.mLock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    t1.start();
    Thread.sleep(400);
    t2.start();
    t1.join();
    t2.join();
}

private static void incrementCount() {

    count++;
    System.out.println("Count: " + count + " icnremented by: " +        Thread.currentThread().getName());
}
}
  class CommonUtil {

 static final Object mLock = new Object();
   }
私有静态整数计数=0; 公共静态void main(字符串[]args)引发InterruptedException{ 线程t1=新线程(新的可运行线程(){ @凌驾 公开募捐{ 对于(int i=0;i<25;i++){ 已同步(CommonUtil.mLock){ 递增计数(); CommonUtil.mLock.notify(); 试一试{ CommonUtil.mLock.wait(); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } } } } }); 线程t2=新线程(新可运行(){ @凌驾 公开募捐{ 对于(int i=0;i<25;i++){ 已同步(CommonUtil.mLock){ 递增计数(); CommonUtil.mLock.notify(); 试一试{ CommonUtil.mLock.wait(); }捕捉(中断异常e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } } } } }); t1.start(); 睡眠(400); t2.start(); t1.join(); t2.连接(); } 私有静态无效增量计数(){ 计数++; System.out.println(“计数:“+Count+”ICN由:“+Thread.currentThread().getName()”)删除); } } 类CommonUtil{ 静态最终对象mLock=新对象(); }
公共类ThreadCounter实现可运行{
私有静态整数计数=0;
私有线程t;
公共线程计数器(字符串tName){
t=新螺纹(此,tName);
t、 start();
}
@凌驾
公开募捐{
对于(inti=1;i我想这可能会有所帮助。
虽然它不是标准的,但我希望它提供了一种更简单的方法

public class ThreadDemo
{
    public static void main (String [] args)
    {
        PrintDemo pd=new PrintDemo();     
        MyThread1 mt1 = new MyThread1 ("T1",pd);
        MyThread2 mt2 = new MyThread2 ("T2",pd);     
        mt1.start ();
        mt2.start();
    }
}
class PrintDemo {
    private boolean oddFlag=true;
    public synchronized void printOdd(int i,String tName){
        if(oddFlag==false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }   
        }else{
            System.out.println("\nThread "+tName+" count:"+i);
            oddFlag=false;
            notify();
        }
    }
    public synchronized void printEven(int i,String tName){
        if(oddFlag==true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }   
        }else{
            System.out.println("\nThread "+tName+" count:"+i);
            oddFlag=true;
            notify();
        }
    }   
}
class MyThread1 extends Thread
{
    private PrintDemo pd;
    private String name;

    MyThread1(String threadName,PrintDemo pd){
        this.name=threadName;
        this.pd=pd;
    }  
    public void run ()  
    {
       for(int i=1;i<=50;i+=2){
            pd.printOdd(i,name);
       }
    }
}
class MyThread2 extends Thread
{
    private PrintDemo pd;
    private String name;    
    MyThread2(String threadName,PrintDemo pd){
        this.name=threadName;
        this.pd=pd;
    }   
    public void run ()
    {
        for(int i=2;i<=50;i+=2){
            pd.printEven(i,name);                   
        }
    }
}
公共类ThreadDemo
{
公共静态void main(字符串[]args)
{
PrintDemo pd=新的PrintDemo();
MyThread1 mt1=新的MyThread1(“T1”,pd);
MyThread2 mt2=新的MyThread2(“T2”,pd);
mt1.start();
mt2.start();
}
}
类PrintDemo{
private boolean oddsflag=true;
公共同步的void printOdd(int i,String tName){
如果(oddFlag==false){
试一试{
等待();
}捕捉(中断异常e){
e、 printStackTrace();
}   
}否则{
System.out.println(“\n读取”+tName+”计数:“+i”);
oddsflag=false;
通知();
}
}
公共同步void print偶数(int i,String tName){
if(oddFlag==true){
试一试{
等待();
}捕捉(中断异常e){
e、 printStackTrace();
}   
}否则{
System.out.println(“\n读取”+tName+”计数:“+i”);
oddsflag=true;
通知();
}
}   
}
类MyThread1扩展了线程
{
私人打印演示pd;
私有字符串名称;
MyThread1(字符串threadName,PrintDemo pd){
this.name=threadName;
这个.pd=pd;
}  
公开作废运行()
{

对于(inti=1;i我遇到了相同的问题,并且希望只使用基本功能,所以我选择了线程间共享对象上的等待通知

public class Message implements Runnable {

    private static final int N = 10;
    private Thread thread;
    private static Object object = new Object();

    public Message(String name){
        thread = new Thread(this, name);
        thread.start();
    }

    public void run(){
        for(int i=0; i<N; i++){
            synchronized (object) {
                System.out.println(i + "--" + thread.getName());
                object.notify();
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}

这是我能想到的最简单的解决方案。它使用同步方法,并使用notify()和wait()交替打印数字。希望能有所帮助。:)

公共类程序实现可运行
{
静态整数计数=1;
私有静态最终整数最大计数=50;
公共同步作废打印()
{
System.out.println(Thread.currentThread().getName()+“正在打印”+计数);
计数++;
通知();
试一试{
如果(计数>最大计数)
返回;
等待();
}捕获(中断异常e){
e、 printStackTrace();
}
}
公开募捐
{
对于(inti=0;i
//只需使用wait和notify,并设置一个计数器,就可以了
公共类ThreadalternatePrint实现可运行{
静态整数计数器=0;
@凌驾
公共同步的无效运行(){
试一试{
睡眠(10);
}捕捉(中断异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
而(计数器
公共类测试实现可运行{
专用静态整数计数器=1;
私有静态最终对象锁=新对象();
公共静态void main(字符串[]args){
线程t1=新线程(新测试(),“1”);
t1.start();
螺纹t2=新螺纹(新测试(),“2”);
t2.start();
}
@凌驾
公开募捐{

而(计数器hi)请在这里找到答案…模式ABABABAB

package com.abhi.ThreadPractice;

    public class Test {

        public static void main(String[] args) throws InterruptedException {

          final Object lock = new Object();
          Thread t1 = new Thread(new Runnable() {

            @Override
           public void run() {
            for (int i = 0; i < 10; i++) {

              synchronized (lock) {
             // count++;
              System.out.println("A");
              try {
               lock.wait();
               lock.notify();
              } catch (InterruptedException e) {
               e.printStackTrace();
              }
             }
            }
           }
          });             

           Thread t2 = new Thread(new Runnable() {

            @Override
           public void run() {
            for (int i = 0; i < 10; i++) {
             synchronized (lock) {
              lock.notify();
              //count++;
              System.out.println("B");
              try {
               lock.wait();
              } catch (InterruptedException e) {
               e.printStackTrace();
              }
             }
            }
           }
          });

           t1.start();
          t2.start();
          t1.join();
          t2.join();

          }

        }
package com.abhi.ThreadPractice;
公开课考试{
public class ThreadCounter implements Runnable {
    private static int count = 0;

    private Thread t;

    public ThreadCounter(String tName){
        t= new Thread(this, tName);
        t.start();
    }

    @Override
    public void run() {
        for(int i=1; i<=5; i++){
            synchronized (CommonUtil.mLock) {
                incrementCount(t.getName());
                CommonUtil.mLock.notify();
                try {
                    CommonUtil.mLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void incrementCount(String tName){
        System.out.println(tName+": "+(++ThreadCounter.count));
    }

    public static void main(String[] args) throws InterruptedException {
        new ThreadCounter("Thread1");
        Thread.sleep(500);
        new ThreadCounter("Thread2");
    }

}

class CommonUtil{
    public static Object mLock = new Object();
}
public class ThreadDemo
{
    public static void main (String [] args)
    {
        PrintDemo pd=new PrintDemo();     
        MyThread1 mt1 = new MyThread1 ("T1",pd);
        MyThread2 mt2 = new MyThread2 ("T2",pd);     
        mt1.start ();
        mt2.start();
    }
}
class PrintDemo {
    private boolean oddFlag=true;
    public synchronized void printOdd(int i,String tName){
        if(oddFlag==false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }   
        }else{
            System.out.println("\nThread "+tName+" count:"+i);
            oddFlag=false;
            notify();
        }
    }
    public synchronized void printEven(int i,String tName){
        if(oddFlag==true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }   
        }else{
            System.out.println("\nThread "+tName+" count:"+i);
            oddFlag=true;
            notify();
        }
    }   
}
class MyThread1 extends Thread
{
    private PrintDemo pd;
    private String name;

    MyThread1(String threadName,PrintDemo pd){
        this.name=threadName;
        this.pd=pd;
    }  
    public void run ()  
    {
       for(int i=1;i<=50;i+=2){
            pd.printOdd(i,name);
       }
    }
}
class MyThread2 extends Thread
{
    private PrintDemo pd;
    private String name;    
    MyThread2(String threadName,PrintDemo pd){
        this.name=threadName;
        this.pd=pd;
    }   
    public void run ()
    {
        for(int i=2;i<=50;i+=2){
            pd.printEven(i,name);                   
        }
    }
}
public class Message implements Runnable {

    private static final int N = 10;
    private Thread thread;
    private static Object object = new Object();

    public Message(String name){
        thread = new Thread(this, name);
        thread.start();
    }

    public void run(){
        for(int i=0; i<N; i++){
            synchronized (object) {
                System.out.println(i + "--" + thread.getName());
                object.notify();
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
Message message1 = new Message("Ping");
Message message2 = new Message("Pong");
 public class program implements Runnable
    {
        static int count =1;
        private static final int MAX_COUNT = 50;
        public synchronized void print ()
        {
            System.out.println(Thread.currentThread().getName() + " is printing " + count);
            count++;
            notify();
            try{
                if(count>MAX_COUNT)
                    return;
                wait();
            }catch (InterruptedException e){ 
                e.printStackTrace();
            }
        }
        public void run()
        {
            for(int i=0;i<MAX_COUNT/2;i++)
            {
                print();

            }
        }

        public static void main(String[] args) {

            program x= new program();
            Thread t0= new Thread(x);
            Thread t1=  new Thread(x);
            t0.start();
            try
            {
                Thread.sleep(1);
            } catch (InterruptedException e){
                e.printStackTrace();
            }
            t1.start();     
        }


    }
//simply use wait and notify and and set a counter and it will do  

public class ThreadalternatePrint implements Runnable {
    static int counter =0; 
    @Override
    public synchronized void run() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        while(counter<51)
        {   ++counter;
        notify();
        System.out.println(Thread.currentThread().getName());
            try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }       
    }

    public static void main(String[] args) {
        ThreadalternatePrint obj1 = new ThreadalternatePrint();
        Thread Th1 = new Thread(obj1);
        Thread Th2 = new Thread(obj1);
        Th1.setName("Thread1");
        Th2.setName("Thread2");
        Th1.start();
        Th2.start();
    }


}
public class Testing implements Runnable {
private static int counter = 1;
private static final Object lock = new Object();

public static void main(String[] args)  {

    Thread t1 = new Thread(new Testing(), "1");
    t1.start();
    Thread t2 = new Thread(new Testing(), "2");
    t2.start();

}

@Override
public void run() {
    while (counter<=100) {
        synchronized (lock) {
            if (counter % 2 == 0) {
                System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                counter++;
                try {
                    lock.notifyAll();
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } else if (counter % 2 == 1) {
                System.out.println(counter +" Written By Thread-"+ Thread.currentThread().getName());
                counter++;

                try {
                    lock.notifyAll();
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
  }
}
package com.abhi.ThreadPractice;

    public class Test {

        public static void main(String[] args) throws InterruptedException {

          final Object lock = new Object();
          Thread t1 = new Thread(new Runnable() {

            @Override
           public void run() {
            for (int i = 0; i < 10; i++) {

              synchronized (lock) {
             // count++;
              System.out.println("A");
              try {
               lock.wait();
               lock.notify();
              } catch (InterruptedException e) {
               e.printStackTrace();
              }
             }
            }
           }
          });             

           Thread t2 = new Thread(new Runnable() {

            @Override
           public void run() {
            for (int i = 0; i < 10; i++) {
             synchronized (lock) {
              lock.notify();
              //count++;
              System.out.println("B");
              try {
               lock.wait();
              } catch (InterruptedException e) {
               e.printStackTrace();
              }
             }
            }
           }
          });

           t1.start();
          t2.start();
          t1.join();
          t2.join();

          }

        }
package com.multithreding.trylock;

import java.util.concurrent.locks.ReentrantLock;

public class TryLock extends Thread {

    static int intitialCount = 50;          //Value till which you want to print
    int valueToSubtract = 0;                //Value by which difference you want to print the series like 1,2,3
    static ReentrantLock alternate = new ReentrantLock();

    public TryLock(String name) {
        this.setName(name);
    }

    public void run() {
        while (intitialCount > 1) {         

            if (valueToSubtract > 0) {
                alternate.lock();
                intitialCount = intitialCount - valueToSubtract;
                valueToSubtract = 0;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("value Subtracted " + intitialCount + " by the Thread" + this.getName());
                alternate.unlock();
            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                valueToSubtract++;
            }
        }

    }

}

package com.multithreding.trylock;

public class AlternatePrint {

    public static void main(String[] args) throws InterruptedException{
        //You  can add as many thread to print then in different number of series
        TryLock t1 = new TryLock("Odd One");
        TryLock t2 = new TryLock("Even Value");
        t1.start();
        t2.start();

    }

}
package thread;

public class Pingpong extends Thread {
    static StringBuilder object = new StringBuilder("");
    static int i=1;

    @Override
    public void run() {
        working();
    }
    void working() {
        while (i<=10) {
            synchronized (object) {
                try {
                    System.out.println(Thread.currentThread().getName() +"  "+ i);
                    i++;
                    object.notify();
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Pingpong();
        Thread t2 = new Pingpong();
        t1.setName("Thread1");
        t2.setName("Thread2");
        t1.start();
        t2.start();
    }
}

Thread1  1
Thread2  2
Thread1  3
Thread2  4
Thread1  5
Thread2  6
Thread1  7
Thread2  8
Thread1  9
Thread2  10