Quantcast
Channel: 懒得折腾
Viewing all articles
Browse latest Browse all 764

PingPong Game

$
0
0
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Program.java
 *
 * Main entry point for game. Creates two threads,
 * Ping and Pong, that alternately display “Ping”
 * and “Pong” respectively on the console.
 */
public class Program {

    public static void main(String[] args) {

        // Create a lock to be acquired by the player thread that is to return the ball.
        // To ensure that each player thread acquires the lock in turn, the fairness
        // parameter is set to true to favor granting access to the longest-waiting thread.
        ReentrantLock lock = new ReentrantLock(true);

        // Countdown latch to ensure that the main thread waits until the player threads
        // are finished before terminating the program.
        CountDownLatch latch = new CountDownLatch(6);

        System.out.println("Ready... Set... Go!");

        // Start playing!
        Player ping = new Player(latch, lock, "Ping!");
        Player pong = new Player(latch, lock, "Pong!");

        try {
            latch.await(); // wait for countdown latch to reach 0
        } catch (InterruptedException e) {
            System.out.println(e);
        } finally {
            // Terminate threads
            ping.terminate();
            pong.terminate();
        }
        System.out.println("Done!");
    }
}

/**
 * Player Thread with safe terminate() method.
 */
class Player implements Runnable {
    private volatile boolean running = true; // thread-safe flag
    private CountDownLatch latch;
    private ReentrantLock lock;
    private String name;

    Player(CountDownLatch latch, ReentrantLock lock, String name) {
        this.latch = latch;
        this.lock = lock;
        this.name = name;
        new Thread(this).start();
    }

    public void terminate() {
        running = false;
    }

    public void run() {

        while (running) // run the thread until it is terminated
        {
            try {
                // Wait for a return from the opponent
                lock.lock(); // acquire the lock (lock() will return when the lock is not owned by another thread)

                if (!running)
                    break; // exit loop if thread is terminated

                // Signal a return
                System.out.println(name);
                latch.countDown(); // decrement count

                Thread.sleep(1000); // sleep for 1 second for simulation and to allow context switch
            } catch (InterruptedException e) {
                System.out.println(e);
            } finally {
                lock.unlock(); // release the lock (letting the other player return the ball)
            }
        }
    }
}
// Cesar De la Paz
// POSA 2013
// Assignment 1 written in Java

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/* The algorithm alterantes between ping and pong by synchronizing
 * with the use of a monitor and a static "turn" variable.  
 * Nofity/Wait are NOT required but useful to prevent wasting computer 
 * resources.  They prevent wasteful loops checking for threadTurn == X
 */
public class PingPong implements Runnable {
    public static Lock lock = new ReentrantLock();
    public static int i = 0;
    public static int threadTurn = 0;

    public void run() {
        while (i < 10) {
            synchronized (lock) {
                if (threadTurn == 0) {
                    System.out.println("Ping!");
                    threadTurn = 1;
                } else {
                    System.out.println("Pong!");
                    threadTurn = 0;
                }
                i++;
                lock.notify();
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        synchronized(lock){ lock.notify();}
    }

    public static void main(String[] args) {
        Thread threadA = new Thread(new PingPong());
        Thread threadB = new Thread(new PingPong());
        System.out.println("Ready... Set... Go!");
        threadA.start();
        threadB.start();
        try {
            threadA.join();
            threadB.join();
        } catch (InterruptedException ignore) {}
        System.out.println("Done!");
    }
}

public class ProgramAssignment1 {
    private Object mLock = new Object();
    private boolean mIsPingPrinted = false;
    private static final String READY_SET_GO = "Ready… Set… Go!";
    private static final String PING = "Ping!";
    private static final String PONG = "Pong!";
    private static final String DONE = "Done!";
    private static final int COUNTER = 5;
    /**
    * Ping thread which prints Ping!
    */
    private class PingThread extends Thread {
        @Override
        public void run() {
            super.run();
            printPing();
        }
        private void printPing() {
            int counter = COUNTER;
            synchronized (mLock) {
                while (counter-- > 0) {
                    if (mIsPingPrinted) {
                        try {
                            mLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(PING);
                    mIsPingPrinted = true;
                    mLock.notify();
                }
            }
        }
    }
    /**
    * Pong thread which prints Pong!
    */
    private class PongThread extends Thread {
        @Override
        public void run() {
            super.run();
            printPong();
        }
        private void printPong() {
            int counter = COUNTER;
            synchronized (mLock) {
                while (counter-- > 0) {
                    if (!mIsPingPrinted) {
                        try {
                            mLock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(PONG);
                    mIsPingPrinted = false;
                    mLock.notify();
                }
            }
        }
    }
    public static void main(String[] args) {
        System.out.println(READY_SET_GO);
        System.out.println();
        ProgramAssignment1 pa1 = new ProgramAssignment1();
        PingThread pingThread = pa1.new PingThread();
        PongThread pongThread = pa1.new PongThread();
        pingThread.start();
        pongThread.start();
        try {
            pingThread.join();
            pongThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(DONE);
    }
}

class Main
{

    private static class MyThread extends Thread
    {
	private static int next_id = 0;
	private static Object lock = new Object();
	
	private String msg;
	private int id;

	private MyThread(String msg, int id)
	{
	    this.msg = msg;
	    this.id = id;
	}

	public void run()
	{	  	    
	    try
		{   
		    for(int i = 0; i < 3; i++)
			{
			    synchronized (lock) {
				if (next_id != id)
				    {
					lock.wait();			    
				    }
			    
				System.out.println(msg);
				next_id = (id == 0) ? 1 : 0;
				lock.notify();
			    }
			}
		}
	    catch (Exception e)
		{
		    System.out.println(e.getClass().getName());
		}			    
	}
    }

    
    public static void main(String[] args) throws InterruptedException
    {
	
	System.out.println("Ready! Set! Go!");
	System.out.println();
	    
	MyThread th1 = new MyThread("Ping!", 0);
	MyThread th2 = new MyThread("Pong!", 1);
	
	th1.start();
	th2.start();
	
	th1.join();
	th2.join();

	System.out.println("Done!");
    }
}


Viewing all articles
Browse latest Browse all 764

Trending Articles