Java Video Tutorial 18

Java ThreadsIn this Java Video Tutorial, I continue to teach you about Java Threads. If you missed the last part, watch it first here last Java Tutorial.

Today I cover how to lock down methods, synchronized, thread pools, scheduleAtFixedRate and numerous other Java Thread methods.

Use the code that follows the video to make it easier to follow this tutorial. It is heavily commented and will help you.

If you like videos like this share it

Code From the Video

LESSONEIGHTEEN.JAVA

// In the last tutorial I coordinated threads using
// a timing method. Here I show you how to execute code based
// on a predefined time schedule and much more

// Used to schedule when certain events should be triggered
import java.util.concurrent.ScheduledThreadPoolExecutor;

// Used to tell Java what unit of time I want to use
import static java.util.concurrent.TimeUnit.*;

public class LessonEighteen{
	
	public static void main(String[] args){
		
		addThreadsToPool();
		
	}
	
	public static void addThreadsToPool(){
		
		// Allows you to schedule code execution at some time in the future
		// You can also have code execute repetitively based on a time period
		// It must be big enough to hold all potential Threads
				
		ScheduledThreadPoolExecutor eventPool = new ScheduledThreadPoolExecutor(5);
				
		// Adds a Thread to the pool. Tells that thread to start executing
		// after 0 seconds (immediately) and then execute every 2 seconds
				
		eventPool.scheduleAtFixedRate(new CheckSystemTime(), 0, 2, SECONDS);
				
		eventPool.scheduleAtFixedRate(new PerformSystemCheck("Mail"), 5, 5, SECONDS);
				
		eventPool.scheduleAtFixedRate(new PerformSystemCheck("Calendar"), 10,10, SECONDS);
		
		// Thread.activeCount returns the number of threads running
		
		System.out.println("Number of Threads: " +Thread.activeCount());
		
		// Quiz: Why does it say there are 4 threads when we expect 3?
		
		// Create an array of threads with enough spaces for all active threads
		
		Thread[] listOfThreads = new Thread[Thread.activeCount()];
		
		// enumerate fills the Thread array with all active threads
		
		Thread.enumerate(listOfThreads);
		
		// Cycle through all the active threads and print out their names
		
		for(Thread i : listOfThreads){
			System.out.println(i.getName());
		}
		
		// Get priority of all the threads (Priority is equal to the thread 
		// that created the new thread. Top priority is 10, lowest priority is 1
		
		for(Thread i : listOfThreads){
			System.out.println(i.getPriority());
		}
		
		// threadName.setPriority can be used to set the priority 
		
		// This allows the above threads to run for approximately 20 seconds
		
		try{
			Thread.sleep(20000);
		}
		catch(InterruptedException e)
		{}
		
		// Shuts down all threads in the pool
		
		// eventPool.shutdown();
		
	}
	
}

CHECKSYSTEMTIME.JAVA

import java.text.DateFormat;
import java.util.*;

public class CheckSystemTime implements Runnable{
	
	public void run(){
		
		Date rightNow;
		Locale currentLocale;
		DateFormat timeFormatter;
		String timeOutput;
		
		rightNow = new Date();
		currentLocale = new Locale("en");
		
		timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
		timeOutput = timeFormatter.format(rightNow);
		
		System.out.println("Time: " + timeOutput);
		
		
	}
	
}

PERFORMSYSTEMCHECK.JAVA

// You could also lock down a method and then unlock it
// when you are finished with it. This library does that

import java.util.concurrent.locks.ReentrantLock;

public class PerformSystemCheck implements Runnable{
	
	private String checkWhat;
	
	// Creates a lock for your method
	
	ReentrantLock lock = new ReentrantLock();
	
	public PerformSystemCheck(String checkWhat){
		
		this.checkWhat = checkWhat;
		
	}
	
	// By putting synchronized before a method, you make
	// sure only one thread at a time can execute it.
	// Synchronizing slows down Java, so it should only
	// be used when necessary.
	
	/* synchronized */ public void run(){
		
		// this locks down the method just like synchronized
		// You can't use synchronized and lock, that's why 
		// synchronized is commented out above
			
		lock.lock();
		
		System.out.println("Checking " + this.checkWhat);
		
		// this unlocks the method just like synchronized
		
		lock.unlock();
		
	}
	
}

25 Responses to “Java Video Tutorial 18”

  1. Guest says:

    Please put the codes of Java Video Tutorial 18 on this page.

  2. Eirik says:

    Hi, great videos! Just wondering about why the TimeUnit library has to be static? Line 3 in JavaLessonEighteen.

    • admin says:

      It doesn’t have to be. I’m not sure why I did that? I improv my way through these tutorials and on occasion I do something silly

      • Eirik says:

        Ok, thank you for quick answer! And the tutorials are just great, have been through 1-24 now and my understanding of Java Programming is so much better than after all the other java tutorials I’ve tried out!

        • admin says:

          Thank you. I’m very happy to hear that. I always wonder who my competition is. I don’t watch any other tutorials so I don’t know what I’m up against.

          • Eirik says:

            There are alot of other talented guys making tutorials on Java, but your pace suits me very well. The others are often a bit slow. Also the fact that you edit your tutorials is as far as I can tell very rare but very nice for us viewers!

            • admin says:

              Well, thank you very much. It is time consuming to edit them, but I think the extra time sets me apart. I’m glad you took the time to say Hi πŸ™‚

  3. jawwad hanif says:

    good work sir, excellent

  4. Aamir says:

    hello derek, i am getting error on line no 30,32,34 . the eclipse throws error “SECONDS cannot be resolved to a variable”.I completely copied this lessons code, i its throwing this error.plz do explain

  5. Lucky says:

    hello derek, i am getting error on line no 30,32,34 . the eclipse throws error “SECONDS cannot be resolved to a variable”.I completely copied this lessons code, i its throwing this error.plz do explain

  6. Lucky says:

    Derek instead of library here i used TIMEUNIT.SECONDS directly as argument so i got perfect result.

  7. MSkiLLz says:

    So this pretty much explains the concept of multi threading? Or is that something else? I would think multi-threading involves running the threads at the same time not scheduled threads.

  8. John says:

    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    SECONDS cannot be resolved to a variable
    SECONDS cannot be resolved to a variable
    SECONDS cannot be resolved to a variable

    at LessonEighteen.addThreadsToPool(LessonEighteen.java:15)
    at LessonEighteen.main(LessonEighteen.java:10)

  9. Sergey says:

    Exception in thread β€œmain” java.lang.Error: Unresolved compilation problems:
    You should write TimeUnit.SECONDS, that`s enum in java except using only SECONDS

  10. Burak says:

    Hi, your video tutorials are awesome!! Thank you for this great vidoes.

    I have a question. Why we used try block in addThreadToPool() method?

    try{
    Thread.sleep(20000);
    }
    catch(InterruptedException e){}

    Best Regard,
    Burak

  11. Yusuf says:

    Is there a limit to how many threads can be started? Is there any type of architecture dependency for threads, like does it have to be multi-CPU etc for the threads to run simultaneously?

Leave a Reply

Your email address will not be published.

Google+