Featured post

Our First Windows

first window

In this part we will discuss the GUI (also referred to HMI for I nterfaces M ike M achine or GUI for G raphicalU ser I nterfaces) and, by extension, event programming. By this, you must understand that your program will not respond to keystrokes but events from a graphical component: a button, list, menu … and this is very important to really grasp when you first want to learn what is java!

The Java language provides different libraries for programming GUI, but in this book we primarily use the packages javax.swing and java.awt present automatically in Java. This chapter will help you learn to use the object JFrame , present in the package java.swing . You will then be able to create a window, set its size, etc.

The basic operation of HMI you will also be presented and you will learn that, in reality, a window is only a multitude of components placed on each other and that everyone has a role of its own.
But enough chatter useless, start now!

The JFrame object

Before we launch headlong into this game, you must know what we will use. In this course we will deal with javax.swing and java.awt . We do not use components awt , we will work only with componentsswing ; however, objects from the package awt will be used to interact and communicate with components swing . For example, a component can be represented by a button, a text box, a check box, etc.

To better understand how it all works, you should know that when Java was born, in version 1.0, only awtwas usable; swing did not exist, he appeared in version 1.2 Java (also called Java 2). The components awtare considered heavy (also called Heavyweight ) as they are strongly linked to the operating system, it is the latter which manages. The components swing themselves are designed in such a container, they are said to light (also called LightWeight ); they do not have the same rendering to the display, because it is no longer the operating system that manages them. There are also other differences, such as the number of usable components, management of borders …

For all these reasons, it is strongly recommended not to mix the components swing and awt in a single window; This could cause conflicts! If you combine the two, you will have great difficulties in developing a stable and valid HMI. Indeed, swing and awt have the same foundation but differ in their use.

This closed parenthesis, we can get into the thick of it. I am not asking you to create a project with a classhand , it must be ready for ages! To use a window type JFrame , you must instantiate it like this:

import javax.swing.JFrame;

 

public  class  Test  {

  public static void main(String[] args){       

    JFrame  fenetre  =  new  JFrame ();

  }       

}

When you run this code, you get nothing, because by default, your JFrame is not visible. So you have to say “be visible” in this way:

import javax.swing.JFrame;

 

public  class  Test  {

  public static void main(String[] args){

    JFrame  fenetre  =  new  JFrame ();

    fenetre.setVisible(true);

  }       

}

So when you run this code, you get the following figure.

what is java

To all those who say that this window is very small, I say, “Welcome to the world of event programming!”We need you to do, your components are not intelligent: he’ll have to tell them everything they need to do.

For a more substantial window should therefore:

  • to be larger;
  • it has a title (this would not be luxury!);
  • it appears in the center of the screen would be perfect;
  • that our program actually stops when you click on the red cross, because for those who have not noticed, the Eclipse process is still running even after closing the window.

For each of the elements I just mentioned, there will be a method to call to our JFrame know what to expect. Here is also a code that meets all our requirements:

import javax.swing.JFrame;

 

public  class  Test  {

  public static void main(String[] args){

 

    JFrame  fenetre  =  new  JFrame ();

 

    // Set a title for our window

    window . setTitle ( 'My first Java window " );

    // Set size: 400 pixels wide and 100 pixels high

    window . setSize ( 400 ,  100 );

    // We now ask our subject to position the center

    window . setLocationRelativeTo ( null );

    // Terminates the process when you click on the red cross

    fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // And finally, make it visible        

    fenetre.setVisible(true);

  }       

}

See the rendering of this code by following figure.

java 8

To avoid having to redefine the attributes each time, I think it would be helpful if we had our own object.That way we’ll have our own classroom!

To start, erase all the code we’ve written in our method hand . Next we create a class we’ll call Window and make it inherit JFrame . We will now create our constructor, in which we place our instructions.
This gives us:

import javax.swing.JFrame;

 

public class Fenetre extends JFrame {

  public  fenêtre () {

    this.setTitle("Ma première fenêtre Java");

    this.setSize(400, 500);

    this.setLocationRelativeTo(null);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);             

    this.setVisible(true);

  }

}

Then you have the choice: either you keep your class containing the method hand and you create an instance of Window or you delete this class and method you put your hand in your class Window . But in all cases, you must create an instance of your Window . Personally, I prefer to put my method hand in a class by itself … But I do not require you to join me! Whatever the location of your hand , the following line of code must be included:

Fenetre  fen  =  new  Fenetre ();

Run your new code, and … you get the exact same thing as before. You will agree that it is still more convenient not to write the same instructions each time. So you have a class that will be responsible for displaying your future program. And here is a list of methods that you will be likely to use.

Position the window on the screen

We have focused our window, but you might want to place it elsewhere. For this you can use the methodsetLocation (int x, int y) . With this method, you can specify which must be your window on the screen. The coordinates in pixels, are based on a benchmark whose origin is represented by the upper left corner (Figure below).

java training

The first value of the method positioned on the axis x , 0 corresponding to the beginning; positive values ​​move the window to the right while negative make it out of the screen from the left. The same rule applies to the values ​​of the axis y , except that the positive values ​​bring down the window from behind while negative make it come out on top of the screen.

Prevent window resizing

To do this, simply invoke the method setResizable (boolean b) : false prevents resizing while truepermits.

Keep the window to the foreground

This is still a method that takes a boolean parameter. Skip true leave the window to the foreground what happens, false void that. This method is setAlwaysOnTop (boolean b) .

Remove the contours and control buttons

To do this, use the method setUndecorated (boolean b) .

I will not go around all methods now because anyway, we’re going to use many of them very prochainement.Cependant, I guess you would rather fill your window. I thought so, but before you must still learn a breast. Indeed, your window, as it appears, you hide a few things!

You think, and that is legitimate, that your window is simple, devoid of any component (excluding contours). Well think again! A JFrame is divided into several overlapping parts, as shown in the following figure.

hiyzd

 

We have, in order:

  • the window;
  • the RootPane(green), the main container that contains other components;
  • the LayeredPane(purple), which just formed a panel composed of the global container and the menu bar ( MenuBar );
  • the MenuBar(in orange), the menu bar, when there is one;
  • the pane happy(pink): it is in this that we will put our components;
  • the GlassPane(transparent) layer used to intercept user actions before they reach the components.

Do not worry, we will use only the content pane. To retrieve it, we just need to use the methodgetContentPane () of the class JFrame . However, we will use a component other than the pane happy: a JPanel in which we will insert our components.

There are other types of window: the JWindow a JFrame borderless and not draggable (movable), and JDialog , a non-resizable window. We do not discuss here, however.

 

 

Eclipse Java Tutorial 6 – Keyboard Shortcuts


Eclipse Keyboard Shortcuts. Become more productive. Eclipse video
tutorial for Beginners. Learn Java programming using Eclipse IDE.
Latest versions of Eclipse : Kepler(4.3), Juno(4.2), Indigo(3.7),
Helios(3.6), Galileo(3.5) Also discussed are productivity tips
including keyboard shortcuts. Visit http://www.rithus.com for more. Play
List :http://www.youtube.com/playlist?list=PLBBog2r6uMCSmPLJMkXXa0lgMFwGScAP8 Tutorial for beginners with examples, Interview Questions and Concepts.

Tutorial Java – 6. Instrucción Break y Continue


Curso completo de Java aquí ► http://bit.ly/CursoJava

En este video aprenderemos el uso y diferencia de las instrucciones break y continue. Aplicaremos su uso dentro de un ciclo for para comprender su funcionamiento.

Síguenos en Twitter: http://twitter.com/codigofacilito
“Like” en Facebook: http://facebook.com/codigofacilito

Suscríbete en YouTube para seguir al tanto con los video tutoriales: http://bit.ly/qHEewR

Nuevos tutoriales de JAVA todos los SÁBADOS aquí en el canal de CódigoFacilito en YouTube.

—–

Twitter de Jorge: http://twitter.com/jorge_vgut
Sitio de Jorge: http://codigoprogramacion.com/

Java in Telugu Basic Concepts of Object Oriented Programming Part 6


Java in Telugu ,ms excel 2007 tutorial in telugu,ms word 2007 tutorial in telugu,c language tutorial for beginners in telugu,
excel 2007 tutorial in telugu,
vlookup in excel 2007 with example in telugu,ms office 2007 tutorials in telugu,,ms access 2007 tutorial in telugu,
tally erp 9 full tutorial in telugu,anu script telugu typing tutorial,photoshop in telugu,ms powerpoint 2007 tutorial in telugu,
pagemaker tutorial in telugu,adobe photoshop tutorial in telugu,
hardware and networking tutorials in telugu,excel tutorial in telugu,ms-excel 2007 tutorial in telugu,
excel in telugu,
telugu excel tutorial,adobe Photoshop in telugu,ms word 2007 in telugu ,
ms word 2007 tutorial in telugu, C basis in telugu, hardware in telugu, web designing in telugu,html in telugu, dreamweaver in telugu, c++ in telugu, java in telugu, autocad in telugu, computer tips in telugu, computer basics in telugu, hacking in telugu, computer tips in telugu

How to Fix Java SE 6 Runtime Issue on Mac OSx Yosemite


This is a very short video, showing you how to fix the legacy Java SE 6 runtime issue, certain applications have, on OSx Yosemite. It’s really simple, just download and install the following package:

http://support.apple.com/downloads/DL1572/en_US/JavaForOSX2014-001.dmg

Apple Download Link (Doesn’t open in Safari):

http://support.apple.com/kb/DL1572

Thanks for Watching, and thanks for staying Subscribed :))

Control your entertainment

java-runtime-settings-3

From here, there is nothing complicated though. We just have to create a new thread when you click the button Go , passing an implementation of Runnable parameter which itself will call the method go () (do not forget to give it to control Boolean true ) .

Here’s the code of our class Window using the thread in question:

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

 

public class Fenetre extends JFrame{

Private  Panneau  pan  =  new  Panneau ();

private JButton bouton = new JButton("Go");

private JButton bouton2 = new JButton("Stop");

private JPanel container = new JPanel();

private JLabel label = new JLabel("Le JLabel");

private  int  counter  =  0 ;

private boolean animated = true;

private boolean backX, backY;

private  int  x ,  and ;

private Thread t;

 

public  fenêtre () {

// The manufacturer has not changed

}

 

private  void  go () {

// The method has not changed

}

 

public  class  BoutonListener  implements  ActionListener {

public void actionPerformed(ActionEvent arg0) {

animated = true;

t = new Thread(new PlayAnimation());

t.start();

button . setEnabled ( false );

bouton2.setEnabled(true);

}

}

 

class Bouton2Listener  implements ActionListener{

public  void  actionPerformed ( ActionEvent  e ) {

animated = false;

bouton.setEnabled(true);

button2 . setEnabled ( false );

}

}

 

class PlayAnimation implements Runnable{

public  void  run () {

go();

}

}

}

Now you finally have control over your animation! We will now be able to decorate it a little in the following chapters.

Depuis Java 7 : le pattern Fork/Join

Version 7 provides Java developers several classes that allow to implement what is called “the pattern Fork / Join”. The latter is nothing more than the implementation of an old saying that you should know: divide and rule! In some cases, it would be good to split a task into subtasks, make these sub-tasks run in parallel and can recover the result of all this once everything is completed. This is exactly what he can do with these new classes. I warn you, it’s a little difficult to understand but it’s really convenient.

Before starting it should be noted that there are a number of prerequisites for this:

  • the machine that will perform the task should have a multi-core processor (2, 4 or more);
  • the task must be divided into several sub-tasks;
  • ensure that there is a real performance gain! In some cases, cut a task makes the treatment longer.

As an example, I offer you to encode a file search (simple as possible to avoid overloading the code). Here are the classes that we will use, for now without management Fork / Join:

ScanException.java

public class ScanException  extends Exception{

  public ScanException(String message){super(message);}

}

FolderScanner.java

import java.io.IOException;

import java.nio.file.DirectoryStream;

import java.nio.file.Files;

import java.nio.file.Path;

public  class  Folder Scanner {

  private Path path = null;

  private String filter = "*";

  privately  Long  Result  =  0 ;

  public  Folder Scanner () {}

  public  Folder Scanner ( Path  p ,  String  f ) {

    path = p;

    filter = f;

  }

 

  /**

  * Method that handles scan folders recursively

  * @throws ScanException

  */

  public long sequentialScan() throws ScanException{

    // If the path is invalid, it throws an exception

    if(path == null || path.equals(""))

      throw  new  ScanException ( "Invalid scanner Path (blank or null)" );

 

      System . out . println ( "Scan folder"  +  path  +  "to search for files with the extension"  +  this . filter );

 

      // Now we list the directory contents to process subfolders

      try(DirectoryStream<Path> listing = Files.newDirectoryStream(path)){          

        for(Path nom : listing){

          // If there is a file, it scans the object through our

          if(Files.isDirectory(nom.toAbsolutePath())){

            FolderScanner f = new FolderScanner(nom.toAbsolutePath(), this.filter);

            result += f.sequentialScan();

          }

        }

      } catch (IOException e) { e.printStackTrace();}

 

      // Now, the content is filtered to the same folder on the defined filter

      try(DirectoryStream<Path> listing = Files.newDirectoryStream(path, this.filter)){

        for(Path nom : listing){

          // For each matching file, we increment our counter

          result++;

        }

      } catch (IOException e) { e.printStackTrace(); }

 

    return result;

  }

}

Et la classe de test : Main.java

import java.nio.file.Path;

import java.nio.file.Paths;

public  class  Main  {

  public static void main(String[] args) {

    Path chemin = Paths.get("E:\\Mes Documents");

    String filtre = "*.psd";

    FolderScanner  fs  =  new  FolderScanner ( path ,  filter );

 

    try {

      Long start = System.currentTimeMillis();

      Long resultat = fs.sequentialScan();

      Long end = System.currentTimeMillis();

      System.out.println("Il y a " + resultat + " fichier(s) portant l'extension " + filtre);

      System.out.println("Temps de traitement : " + (end - start));

    } catch (ScanException e) {

      and . printStackTrace ();

    }

  }

}

When I run this code processing time is really long (I have many folders in My Documents ), as shown in the following figure.

iopyiutrf

We can see that it is possible to cut the scan each file in a sub-task, and that is exactly what we will do. To do this, we must inherit our class FolderScanner of classes for this division. Java 7 platform puts us provide two classes that inherit from the abstract class ForkJoinTask <V> :

  • RecursiveAction : class to split a task that returns no particular value. It inherits ForkJoinTask <Void> ;
  • RecursiveTask <V> : same as the previous class but returns a value, type <V> at the end of treatment. It is this class that we’ll use in case we return the number of files found.

We’ll have to use, in addition to the cutting object, an object that will have the role of supervising the execution of tasks and sub-tasks in order to merge the threads at the end of treatment: ForkJoinPool .

Before introducing the complete code, here’s how it works. Objects that allow the division into subtasks provide three methods for this management:

  • compute () : abstract method to redefine the object inheriting in order to define the treatment to be performed;
  • fork () : method that creates a new thread in the thread pool ( ForkJoinPool );
  • join () : method to retrieve the result of the method compute () .

These classes require you to reset it the method compute () to define what there is to do. The figure below is a diagram showing how things go.

fork

Specifically, with our example, here’s what will happen:

  • we will start scanning our file;
  • our object is used to scan the content will check the contents to see if there are no subfolders;
  • for each subfolder, we will create a new task and launch;
  • we will count the number of files that match our criteria in the scan current folder;
  • we will get the number of files found by executions in the background;
  • we will return the final result.

For you to understand, here are some of my folder My Documents :

java 59

And actually this is what will happen:

jlkg

We can now see the code section.

FolderScanner.java

public class FolderScanner extends RecursiveTask<Long>{

  private Path path = null;

  private String filter = "*";

  privately  Long  Result  =  0 ;

 

  public  Folder Scanner () {}

  public  Folder Scanner ( Path  p ,  String  f ) {

    path = p;

    filter = f;

  }  

 

  /**

   * We use single thread mode scan

   * @throws ScanException

   */

  public long sequentialScan() throws ScanException{

    // If the path is invalid, it throws an exception

    if(path == null || path.equals(""))

      throw  new  ScanException ( "Invalid scanner Path (blank or null)" );

 

    System . out . println ( "Scan folder"  +  path  +  "to search for files with the extension"  +  this . filter );

 

    // Now we list the directory contents to process subfolders

    try(DirectoryStream<Path> listing = Files.newDirectoryStream(path)){      

      for(Path nom : listing){

        // If there is a folder, you scan through our object

        if(Files.isDirectory(nom.toAbsolutePath())){

          FolderScanner f = new FolderScanner(nom.toAbsolutePath(), this.filter);

          result += f.sequentialScan();

        }

      }

 

    } catch (IOException e) {   e.printStackTrace();  }

 

    // Now, the content is filtered to the same folder on the defined filter

    try(DirectoryStream<Path> listing = Files.newDirectoryStream(path, this.filter)){

      for(Path nom : listing){

        // For each matching file, we increment our counter

        result++;

      }

    } catch (IOException e) {  e.printStackTrace(); }

 

    return result;

  }

 

  /**

   * Method that we will use for treatments

   * In parallel mode.

   * @throws ScanException

   */

  public long parallelScan() throws ScanException{

    // List object that will contain the created subtasks and launched

    List<FolderScanner> list = new ArrayList<>();

 

    // If the path is invalid

    if(path == null || path.equals(""))

      throw  new  ScanException ( "Invalid scanner Path (blank or null)" );

 

    System . out . println ( "Scan folder"  +  path  +  "to search for files with the extension"  +  this . filter );

 

    // We list, as before, the directory contents

    try(DirectoryStream<Path> listing = Files.newDirectoryStream(path)){

      // It scans the contents

      for(Path nom : listing){

        // If there is a folder, a sub-task is created

        if(Files.isDirectory(nom.toAbsolutePath())){

          // So we create a new object FolderScanner

          // Who will scan that folder

          FolderScanner f = new FolderScanner(nom.toAbsolutePath(), this.filter);

          // We add it to the list of current tasks to get the result later

          list.add(f);

          // This is the instruction that initiates the action in the background

          f.fork();

        }

      }

    } catch (IOException e) {

      and . printStackTrace ();

    }

 

    // There are now the files matching the filter, in this folder

    try(DirectoryStream<Path> listing = Files.newDirectoryStream(path, this.filter)){

      for(Path nom : listing){

        result++;

      }

    } catch (IOException e) {

      and . printStackTrace ();

    }

 

    // And finally, we get the results of all background tasks

    for(FolderScanner f : list)

      result += f.join();

 

    // We refer the end result

    return result;    

  }

 

  /**

   * Method which defines the action to do

   * In our case, we CONS lan scanning in parallel fashion

   */

  protected Long compute() {

    long  result  =  0 ;

    try {

       resultat = this.parallelScan();

    } catch (ScanException e) {

      and . printStackTrace ();

    }

    return  result ;

  }

 

  public long getResultat(){  return this.result; }

 

}

And now here is our test class:

import java.nio.file.Path;

import java.nio.file.Paths;

import  java . useful . concurrent . ForkJoinPool ;

 

public  class  Main  {

  public static void main(String[] args) {

    Path chemin = Paths.get("E:\\Mes Documents");

    String filtre = "*.psd";

 

    // Create our main task is responsible for his work cut into subtasks

    FolderScanner  fs  =  new  FolderScanner ( path ,  filter );

 

    // We get the number of processors available

    int processeurs = Runtime.getRuntime().availableProcessors();

    // We create our thread pool for our background tasks

    ForkJoinPool  pool  =  new  ForkJoinPool ( processors );

    Long start = System.currentTimeMillis();

 

    // We launch our main processing task using the pool

    pool.invoke(fs);

 

    Long end = System.currentTimeMillis();

    System.out.println("Il y a " + fs.getResultat() + " fichier(s) portant l'extension " + filtre);

    System.out.println("Temps de traitement : " + (end - start));    

  }

}

To give you an idea, the single thread mode scan of my folder My Documents takes an average of 2 minutes, while the average time Fork / Join fashion is about … 10 seconds! Not bad, eh?

The following figure shows the use of my processors.

aqw

 

You will find that the use of this mode is very resource intensive processors. It is therefore used sparingly.

In this example we have created dynamically as many threads as needed to address our tasks. You may not need to do this for problems where only 2 or 3 subtasks enough, especially if you know in advance. The thrust is equivalent to setting a threshold beyond which the treatment will be done Fork / join mode, otherwise it will be in a single thread (I remind you it may be that this mode is slower and consumer in normal mode). Here is how to proceed in such cases:

import  java . useful . concurrent . ForkJoinPool ;

import  java . useful . concurrent . RecursiveTask ;

public class CalculSuite extends RecursiveTask<Long> {

  Private  long  debut  =  0 ,  fin  =  0 ,  results ;

  private  int  Seuil  =  1 _000 ;

  public CalculSuite(long debut, long fin){

    this.debut = debut;

    this.fin = fin;

  }

  protected Long compute() {

    long nombreDeChoseAFaire = fin - debut;

    if(nombreDeChoseAFaire < SEUIL){

      System . out . println ( "Passage single-threaded mode or cutting calculation result" );

      result  =  calculate ();      

    }

    else{

      System.out.println("Passage en mode Fork/Join");

      // The task is cut into two

      long  mid  =  nombreDeChoseAFaire / 2 ;

      CalculSuite calcul1 = new CalculSuite(debut, (debut+milieu)-1);

      calcul1.fork();

 

      CalculSuite  calculation2  =  new  CalculSuite ( beginning  +  middle ,  end );

      resultat = calcul2.compute() + calcul1.join();      

    }    

    return  result ;

  }

 

  public  long  calculate () {

 

    for(long i = debut; i <= fin; i++){

      System.out.println(resultat + " + " + i);

      resultat += i;      

    }

    return  result ;

  }

 

  public  long  GetResult () {   return  result ; }

 

  public static void main(String[] args){

    ForkJoinPool pool = new ForkJoinPool();

    CalculSuite  calculation  =  new  CalculSuite ( 0 , 100 _000 );

    pool.invoke(calcul);

    System . out . println ( "Calculation result:"  +  computing . getResultat ());

  }

}

You can see that this code works fine even if his interest is only teaching.

  • A new thread creates a new execution stack.
  • The class Thread and interface Runnable are in the package java.lang , no specific import is therefore necessary for their use.
  • A thread starts when invokes the method start () .
  • It automatically invokes the method run () .
  • The operations you want to perform in another execution stack should be placed in the method run () , whether a class inheriting Thread or an implementation of Runnable .
  • To protect the integrity of data accessible to multiple threads, use the keyword synchronized in the declaration of your methods.
  • A thread is declared dead when he popped the method run () its execution stack.
  • Les threads peuvent présenter plusieurs états : NEW, RUNNABLE, BLOCKED, WAITING,TIMED_WAITING et TERMINATED.

 

Use Runnable Interface

Multithread_ThreadRunnable

Do redefine the tasks that the new thread should perform includes another advantage: we have the class does not inherit from any other! Yes: in our previous test, the class TestThread can not inherit from a class, while with an implementation of Runnable , nothing prevents our class to inherit JFrame , for example …

Truce chatter: codons our implementation of Runnable . You should have no problem to do so, knowing that only the method run () to redefine.

To illustrate this, let’s use an example that I found interesting when I learned how to use threads: we create an object BankAccount containing a default amount of money (say 100), a method withdraw money ( retraitArgent () ) and a method returning the balance ( getSolde () ). However, before removing the money, we will verify that we are not short … Our thread will perform as many operations as we wish. The following figure shows the class diagram summarizing the situation.

application-thread

I summarize:

  • Our application can contain one or more objects Thread  ;
  • these can only be composed of one type of object Runnable  ;
  • in our case, the objects Thread contain an implementation of Runnable  : RunImpl  ;
  • this implementation has an object BankAccount .

Here are the source codes …

RunImpl.java

public  class  RunImpl  implements  Runnable  {

  private  CompteEnBanque  cb ;

  public  RunImpl ( CompteEnBanque  cb ) {

    this.cb = cb;

  }

  public  void  run () {

    for(int i = 0; i < 25; i++){

      if(cb.getSolde() > 0){

        cb.retraitArgent(2);

        System.out.println("Retrait effectué");

      }                       

    }               

  }

}

CompteEnBanque.java

public  class  CompteEnBanque  {

  private  int  solde  =  100 ;

  public  int  getSolde () {

    if(this.solde < 0)

      System . out . println ( "You are short!" );

    return  this . balance ;

  }

  public  void  retraitArgent ( int  withdrawal ) {

    balance  =  balance  -  withdrawal ; 

    System.out.println("Solde = " + solde);                 

  }

}

Test.java

public  class  Test  {

  public static void main(String[] args) {

    CompteEnBanque  cb  =  new  CompteEnBanque ();

    Thread t = new Thread(new RunImpl(cb));

    t.start();

  }

}

This gives us the following figure.

console

Nothing extraordinary here, a simple loop would have done the same thing. Add a name to our implementation and create a second thread using a second account. We must think of change the implementation so that we can know the thread that works:

public  class  RunImpl  implements  Runnable  {

  private  CompteEnBanque  cb ;

  private  String  name ;

  public  RunImpl ( CompteEnBanque  cb ,  String  name ) {

    this.cb = cb;

    this.name = name;

  }

  public  void  run () {

    for(int i = 0; i < 50; i++){

      if(cb.getSolde() > 0){

        cb.retraitArgent(2);

        System.out.println("Retrait effectué par " + this.name);                       

      }                       

    }               

  } 

}

public  class  Test  {

  public static void main(String[] args) {

    CompteEnBanque  cb  =  new  CompteEnBanque ();

    CompteEnBanque  CB2  =  new  CompteEnBanque ();

 

    Thread t = new Thread(new RunImpl(cb, "Cysboy"));

    Thread t2 = new Thread(new RunImpl(cb2, "Zéro"));

    t.start();

    t2.start();

  }

}

So far, nothing disturbing: we used two separate instances of RunImpl themselves using two separate instances of BankAccount . But what would happen if we used the same instance of BankAccount for two different threads? Test several times the code here:

public  class  Test  {

  public static void main(String[] args) {

    CompteEnBanque  cb  =  new  CompteEnBanque ();

 

    Thread t = new Thread(new RunImpl(cb, "Cysboy"));

    Thread t2 = new Thread(new RunImpl(cb, "Zéro"));

    t.start();

    t2.start();

  }

}

The figure below shows two pieces of results obtained during execution.

java masteration

You can see monumental inconsistencies! I guess you thought like me that the account was not debited by two to the end without getting aberrations of this kind, since we use the same object … Well, no! Why? Just because the scheduler instead of Java threads sleep when he wants, and when the thread that was dormant awakens, he resumed his work where he left off!

Let’s see how to solve this problem.

Synchronize its threads

Everything is in the title! In fact, you need to do is tell the JVM that thread is to use data that another thread is likely to alter.

So when the scheduler goes to sleep a thread that dealt with data used by another thread, the first thread retains priority over data and until it has completed its work, other threads do not the possibility to touch it.

This is called synchronize threads . This operation is very difficult and requires a lot of programming skills … looks like this our method retraitArgent () synchronized:

public  class  CompteEnBanque  {

  // The beginning of the code does not change

  public  synchronized  void  retraitArgent ( int  withdrawal ) {

    balance  =  balance  -  withdrawal ;

    System.out.println("Solde = " + solde);

  }

}

Just add in the declaration of the method the keyword synchronized , whereby the method is inaccessible to a thread if it is already used by another thread. Thus, threads seeking to use the methods already supported by another thread are placed in a “waiting list”.

I recapitulate again, serving me with a simple example. I will be represented by the thread A you by thread B, and our favorite bakery in the synchronized method M. Here’s what happens:

  • thread A (me) calls the method M;
  • I begin by asking a wand: the baker laying me on the counter and starts calculating the amount;
  • this is where the thread B (you) also seeks to use the method M; however, it is already occupied by a thread (me);
  • so you are put on hold;
  • the action returns to me (thread A); when you pay, I have to get some money in my pocket;
  • After a few moments, I fall asleep;
  • the action returns to the thread B (you) … but the method M is still not released from the thread A, so you are given pending;
  • Returning to the thread A which finally comes to pay and leave the bakery: the method M is now free;
  • thread B (you) can finally use the method M;
  • and there the threads C, D, E and F enter the bakery;
  • and so on.

I think because of that, you had to understand …

In a computing environment, it can be convenient and secure to use threads and synchronized methods in access to remote services such as an application server or a DBMS (Database Management System).

I now propose to return to our animation, which is waiting a little thread to run correctly!

 

Java Design Patterns and Architecture Part 6


OBSERVER PATTERN: THE THEORY

If you are a beginner when it comes to the Java programming language or even if you are an experienced programmer looking for some new tips&tricks, the best thing to do, and which has the advantage of being absolutely free of charge, is to search the Internet for Java tips and Java tutorials.

Try this instead of buying one or two books, and you are going to be impressed by the quantity of information you’ll find available about the domain. This is the easiest way to access tons of Java tutorials or a lot of very useful Java tips with no effort and no cost at all.

The Java programming language and platform were first developed during the early nineties and a few years later it was re-designed for use in the Internet, and since then its popularity greatly increased, especially on the server side of the Internet.

Nowadays there are quite a lot of Java experts and a lot of documentation on this subject has been written, so if you are a beginner start searching for Java tutorials to learn more, and if you are an advanced user, you can always make use of the large number of Java tips that can be found and that can help you solve almost every problem you encounter in your path to making perfect Java programs.

Even for those who are ablsolute beginners in learning about Java, better and easier than attending courses is learning from the Internet Java tutorials. They can find anything from getting started, the basics of the Java language, essential classes, to more specialized tutorials like security in Java, graphics, working with databases and many more things. You can find websites that are specialized in giving Java tips and Java tutorials to those who need. Those tutorials and tips are written by experts and are placed in categories, which helps you immediately find the Java tips or the Java tutorials that you are looking for. The best thing when learning is to read more Java tutorials, and to combine the Java tutorials you learn from with the short and useful Java tips you find.

On the other side, if you are an experienced programmer and you want to share your knowledge, you can begin writing Java tutorials and Java tips to help the newbies and other who need it.

Article Source: http://EzineArticles.com/157179

Resources:
https://www.java.com/en/
www.caveofprogramming.com
http://www.oracle.com/technetwork/java/index.html
http://blog.teamtreehouse.com/learn-java
http://www.oracle.com/technetwork/articles/javase/index-jsp-138363.html
http://en.wikipedia.org/wiki/Java_(programming_language)
https://www.oracle.com/java/index.html
http://en.wikipedia.org/wiki/Java_(software_platform)
http://en.wikipedia.org/wiki/Java
http://support.apple.com/kb/dl1572

Related Search :
Java Design Patterns and Architecture Part 1,Java Design Patterns,Java Design Patterns and Architecture, java programming tutorial,java tutorial,javascript,java programming,java tutorial for beginners,javascript tutorial for beginners,java,java10011

Disclaimer : This Video Does Not Represent “Java ” officially. This tutorial is solely for education purposed only.

Credits to Udemy

Mac El Capitán Fix – This application requires the legacy Java SE 6 runtime – CC


How to fix this application requires the legacy Java SE 6 runtime which is unavailable for this version of the OS X

If anyone is using the beta version of El Capitán and need to downgrade their Java to 6 here is what worked for me
I got all my applications working again after the upgrade – Thought I would share.

How to fix and install Java SE 6 errors in El Capitan

How to Fix Java SE 6 Runtime Issue on Mac OS X 10.11 El Captain

1. Download Apple’s Java Package from https://support.apple.com/kb/DL1572?locale=en_US

2. Download Pacifist – https://www.charlessoft.com

3. Download UninstallPKG – http://www.corecode.at/uninstallpkg/

4. open UninstallPKG app search for Jdk and uninstall any version of JDK on your Mac

5. open the JavaForOSX.dmg and Drag it to JavaForOSX.pkg

from JavaForOSX2014-001.dmg to your desktop

6. Run this command

sudo nvram boot-args=”rootless=0″;osascript -e ‘tell app “loginwindow” to «event aevtrrst»’

7. After your computer restarts Drag JavaForOSX.pkg and onto the Pacifist application to open it.

8. click on the JavaForOSX.pkg” and install it with administrator privileges.

9. now click and install JavaForOSX.pkg
___________________________________

How to downgrade Java from 8 to 6 in Mac OS X El Captian 10.11

How to Run Minecraft Launcher in OS X 10.11

use these tips at your own risk Use these tips at your own risk

If you Don’t have it already Get the Beta version of Mac OS X El Captain 10.11 here

macos 10.10

https://beta.apple.com/sp/betaprogram/welcome

If you get any errors with the commend line try this

http://1i0ny.de/apps/rootlesstoggler/download.php