Multithreading

I'm trying to create a program that uses threads to display Ping Pong.The threads should be prioritized so that one will run before the other. The high priority "Ping" thread should execute and then delay execution of lower thead "Pong".

I cant get the threads to prioritize correctly and i need help with how to do the code to delay the other thread.


import java.lang.Thread;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
 
 
public class HighPriorityPingPong
{
    public static void main( String[] args)
    {
        // print program title
        System.out.println("Display Ping - Pong ");
 
        //thread for ping and thread for pong
        Thread threadPing = new PrintThread("Ping");
        Thread threadPong = new PrintThread("Pong");       
 
        // set priorities
        threadPing.setPriority(10  ); // set to highest priority
        threadPong.setPriority(1   ); // set to lowest priority
       
       threadPing.start();
       threadPong.start();  
 
 
    }
 
}
 
// print thread
class PrintThread extends Thread
{
 
    private  int pauseTime;
    private  String taskName;
//    private final static Random generator = new Random();
 
    public PrintThread( String name)
    {
    taskName = name;
 
    // print time
    pauseTime = 2000;
    }
 
    public void run()
    {
        while(true)
        {
			try
		   {
				Thread.sleep(pauseTime); // snooze
			}
		   catch (InterruptedException exception)
			{
				System.out.printf("%s %s\n", taskName, "Interrupted");
 
			}
        // print thread name
        System.out.printf("%s \n", taskName);
        }
    }
 
}

Open in new window

epalmer86Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hazgodukCommented:
I think the priority would only come into effect if the processor is busy
0
anilallewarCommented:
If you want that first PIng should execute and only after that you want pong to execute, that can be done using a producer-consumer scenario with shared monikor. In this case PIng would be the producer and Pong would be the consumer.

Please find the source code attached.
package com.anil.java.threads;
 
public class HighPriorityPingPong {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Create a common item that would be passed to the Producer and
		// Consumer
		PrintItem item = new PrintItem();
		PrintThreadProducer p1 = new PrintThreadProducer(item, "Ping");
		PrintThreadConsumer c1 = new PrintThreadConsumer(item, "Pong");
 
		// Create thread that would run the target consumer and producer
		Thread t1 = new Thread(p1);
		Thread t2 = new Thread(c1);
		// Start the thread and observe the output. Note we are starting the
		// consumet thread
		// first and then the producer thread
		t2.start();
		t1.start();
	}
 
}
 
class PrintItem {
	private int contents = 0;
	private boolean available = false;
 
	// synchonize the get and set methods
	/**
	 * Get the data once it becomes available and wait till it is available
	 */
	public synchronized int get() {
		// If the content is not available then wait
 
		while (available == false) {
			try {
				this.wait();
			} catch (InterruptedException ie) {
				System.out
						.println("Got interrupted exception while waiting for contents: "
								+ ie.getMessage());
			}
		}
		// Set available to false indicating that the contents have been
		// consumed
		this.available = false;
		// Notify all the waiting threads that are waiting for locks on this
		// object
		// Note that the lock is NOT released till the time the Thread completes
		// execution
		// of this synchronized method
		this.notifyAll();
		// retun contents
		return contents;
	}
 
	public synchronized void put(int contents) {
		// If the content is already available, then wait till the content is
		// consumed
		while (this.available == true) {
			try {
				this.wait();
			} catch (InterruptedException ie) {
				System.out
						.println("Got interrupted exception while waiting for contents: "
								+ ie.getMessage());
			}
		}
		// set the content
		this.contents = contents;
		// Set available to true indicating that content will be populated once
		// control
		// moves out of this method
		this.available = true;
		// Notify all waiting thread that need lock on this object
		this.notifyAll();
	}
}
 
class PrintThreadProducer implements Runnable {
	PrintItem item = null;
	String name = null;
 
	// The constructor initializes the null objects
	PrintThreadProducer(PrintItem item, String name) {
		this.item = item;
		this.name = name;
	}
 
	// Implement the run method
	public void run() {
		for (int i = 1; i <= 10; i++) {
			this.item.put(i);
			System.out.println("Producer " + this.name + " put the content: "
					+ i);
			try {
				Thread.sleep((int) (Math.random() * 100));
			} catch (InterruptedException e) {
				System.out.println("Got interrupted ");
			}
 
		}
	}
}
 
class PrintThreadConsumer implements Runnable {
	PrintItem item = null;
	String name = null;
 
	// The constructor initializes the null objects
	PrintThreadConsumer(PrintItem item, String name) {
		this.item = item;
		this.name = name;
	}
 
	// Implement the run method
	public void run() {
		int value;
		for (int i = 1; i <= 10; i++) {
			value = this.item.get();
			System.out.println("Consumer " + this.name + " GOT the content: "
					+ value);
		}
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
epalmer86Author Commented:
Thank you anil, that helped alot.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.