Java Multithreading / Concurrency - code / coding

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Thread - date

*Date now = new Date();* We can get the date and time by constructing a Date object:

Thread - running a thread

// This program runs two greeting threads in // parallel. public class GreetingThreadRunner { public static void main(String[] args) { GreetingRunnable r1 = new GreetingRunnable("Thread 1 Running"); GreetingRunnable r2 = new GreetingRunnable("Thread 2 Running"); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } }

Thread - running a thread

Create an object of your subclass: *Runnable r = new MyRunnable();* Construct a Thread object from the runnable object: *Thread t = new Thread(r);* Call the start method to start the thread: *t.start();*

Thread - terminate - interrupt

The run method should check occasionally whether it has been interrupted. Use the interrupted method An interrupted thread should release resources, clean up, and exit: public void run() { for (int i = 1; i <= REPETITIONS && !Thread.interrupted(); i++) { Do work } Clean up }

Thread - lock & unlock

balanceChangeLock.lock(); balanceChangeLock.unlock(); If code between calls to lock and unlock throws an exception, call to unlock never happens..... To overcome this problem, place call to unlock into a finally clause: public void deposit (double amount) { balanceChangeLock.lock(); try { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; } finally { balanceChangeLock.unlock(); } }

Thread - stop - using boolean

class MyThread extends Thread { //Initially setting the flag as true private volatile boolean flag = true; //This method will set flag as false public void stopRunning() { flag = false; } @Override public void run() { //Keep the task in while loop //This will make thread continue to run until flag becomes false while (flag) { System.out.println("I am running...."); } System.out.println("Stopped Running...."); } } public class MainClass { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //call stopRunning() method whenever you want to stop a thread thread.stopRunning(); } } output: I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... Stopped Running....

Thread - stop - using interrupt

class MyThread extends Thread { @Override public void run() { while (!Thread.interrupted()) { System.out.println("I am running...."); } System.out.println("Stopped Running....."); } } public class MainClass { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //interrupting the thread thread.interrupt(); } } output: I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... I am running.... Stopped Running.....

Thread - repeatedly prints a greeting

import java.util.Date; // A runnable that repeatedly prints a greeting. public class GreetingRunnable1 implements Runnable { private int REPETITIONS = 10; private static final int DELAY = 1000; // 1000 milliseconds private String greeting; // Constructs the runnable object. // @param aGreeting the greeting to display public GreetingRunnable1(String aGreeting) { greeting = aGreeting } public void run() { try { if (greeting.equals("Thread 1 Running")) for (int i = 1; i <= REPETITIONS; i--) { Date now = new Date(); System.out.println(now + " " + greeting); Thread.sleep(DELAY); } else for (int i = 1; i <= REPETITIONS; i++) { Date now = new Date(); System.out.println(now + " " + greeting); Thread.sleep(DELAY); } } catch (InterruptedException exception) { } } }

Thread - interrupt method

package com.tutorialspoint; import java.lang.*; public class ThreadDemo implements Runnable { Thread t; ThreadDemo() { t = new Thread(this); System.out.println("Executing " + t.getName()); // this will call run() fucntion t.start(); // interrupt the threads if (!t.interrupted()) { t.interrupt(); } // block until other threads finish try { t.join(); } catch(InterruptedException e) {} } public void run() { try { while (true) { Thread.sleep(1000); } } catch (InterruptedException e) { System.out.print(t.getName() + " interrupted:"); System.out.println(e.toString()); } } public static void main(String args[]) { new ThreadDemo(); new ThreadDemo(); } } *output*: Executing Thread-0 Thread-0 interrupted:java.lang.InterruptedException: sleep interrupted Executing Thread-1 Thread-1 interrupted:java.lang.InterruptedException: sleep interrupted

Thread - lock

public class BankAccount { private Lock balanceChangeLock; public BankAccount() { balanceChangeLock = new ReentrantLock(); ....... } ......}

Thread - code runs two greeting threads in parallel

public class GreetingThreadRunner { public static void main(String[] args) { GreetingRunnable r1 = new GreetingRunnable("Hello, World!"); GreetingRunnable r2 = new GreetingRunnable("Goodbye, World!"); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); } } // if the code was changed, and the main method // called below, instead of starting threads.... *r1.run();* *r2.run();* then the 1st call to *run* would print 10 "Hello" messages, and the 2nd call to run would print ten "Goodbye" messages.

Thread - Runnable Interface Implementation

public class MyRunnable implements Runnable { public void run(){ System.out.println("MyRunnable running"); } } public static void main(String[] args){ Thread thread = new Thread(new MyRunnable()); thread.start(); }

Thread - sleep

sleep(milliseconds) *Thread.sleep(1)* .... 1 millisecond

Thread - terminate - interrupt

t.interrupt(); // interrupt does not cause the thread to terminate... it sets a boolean variable in the thread data structure


Kaugnay na mga set ng pag-aaral

Chapter 2 Psych: Life span development

View Set

Developmental Psychology - Ch.1 - Understanding Human Development: Approaches and Theories

View Set

Characterization, Theme, and Irony in "The Gift of the Magi"

View Set

Civil Rights vocabulary and Supreme Court Decisions

View Set

Knowledge Check: BOH Practice Test 3Q22.0

View Set