Java Threads

Jussi Pohjolainen

TAMK University of Applied Sciences » ICT

What are threads?

Making a thread

1. Extending java.lang.Thread

1. Example of Extending java.lang.Thread

class MyThread extends Thread {
    int i = 0;
    public void run() {
        while( true ) {
            System.out.println(i++);
        }
    }
    public static void main(String [] args) {
        ( new MyThread() ).start();
    }
}

2. Implementing java.lang.Runnable

2. Example of Implementing java.lang.Runnable

class MyThread implements Runnable {
    int i = 0;
    public void run() {
        while( true ) {
            System.out.println(i++);
        }
    }
    public static void main(String [] args) {
        Thread thread = new Thread( new MyThread() );
        thread.start();
    }
}

Thread states

Starting a thread

Influencing the thread

Thread priorities

class MyThread extends Thread {
    private static Time time;
    
    private int number;
  
    public void run() {
        while( time.getTime() >= 0 ) {
            System.out.println( Thread.currentThread().getName() );
            number++;
        }
        System.out.println(Thread.currentThread().getName() + " Number of execution: " + number);
    }
    
    public static void main(String [] args) {
        MyThread thread1 = new MyThread();
        thread1.setName("Min");
        MyThread thread2 = new MyThread();
        thread2.setName("Max");
        
        time = new Time();
        thread1.setPriority(1);
        thread2.setPriority(10);
        
        time.start();
        thread1.start();
        thread2.start();
    }
}

class Time extends Thread {
    private int time = 10;
    
    public int getTime() {
        return time;
    }
    
    public void run() {
        while(time >= 0) {
            time--;
            try {
                sleep(1000);
            } catch( InterruptedException e ) {
                e.printStackTrace();
            }
        }
    }
}

yield()

Synchronizing Code

class AccountDanger implements Runnable {
	private Account acct = new Account();
	
	public static void main(String [] args){
		AccountDanger r = new AccountDanger();
		Thread lucy = new Thread(r, "Lucy");
		Thread fred = new Thread(r, "Fred");
		lucy.start();
		fred.start();
	}
	public void run() {
		for(int x = 0; x < 5; x++){
			makeWithdrawal(10);
			if(acct.getBalance() < 0 ){
				System.out.println("account is overdrawn!");
			}
		}
	}
	private void makeWithdrawal(int amt) {
		if(acct.getBalance() >= amt){
			System.out.println(Thread.currentThread().getName() + " is going to withdraw!");
			try{
				Thread.sleep(500);
			}
			catch(InterruptedException ex){}
			acct.withdraw(amt);
			System.out.println(Thread.currentThread().getName() + " completes the withdrawal!");
		}
		else{
			System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance());
		}
	
	}

}

class Account{
	private int balance = 50;
	public int getBalance() {
		return balance;
	}
	public void withdraw(int amount) {
		balance = balance - amount;
	}
}

Synchronized - keyword

Synchronized - example 1

Synchronized - example 2

Synchronized - example 3


class MyThread implements Runnable {
    private Vector list;
    public MyThread(Vector list) {
        this.list = list;
    }
    public void run() {
        synchronized(list) {
            list.add("a");
            list.add("b");            
            for (String s : list) {
                System.out.println(s);
            }
            System.out.println("* *");
        }
    }
    public static void main(String [] args) {
        Vector list = new Vector();
        MyThread temp = new MyThread(list);      
        Thread thread1 = new Thread(temp);
        Thread thread2 = new Thread(temp);
        thread1.start();
        thread2.start();
    }
}