An error will occur on Java if you perform unexpected processing such as dividing by 0. (Runtime error) It is necessary to use try, catch, finally blocks as a way to handle exception error handling on java.
try~catch statement
try{
try block
The process you want to execute
}
catch(Exception type Variable name) {
catch block
What to do when an exception is thrown
}
finally {
finally block
The last process that must be done
}
sample1(Division by zero)
public class test1 {
public static void main(String[] args) {
//TODO auto-generated method stub
int a=2;
int b=100;
try {
int c = b/a;
System.out.println(c);
}
catch(ArithmeticException e) {
System.out.println("Exception occurred");
System.out.println(e);
return;
}
finally {
System.out.println("End Program");
}
}
}
sample2(Non-existent array specification)
class SimpleClass{
void doSomething() {
int array[] = new int[3];
array[10]=999;
System.out.println("Exit the doSomething method");
}
}
public class test2 {
public static void main(String[] args) {
SimpleClass obj = new SimpleClass();
try {
obj.doSomething();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occurred");
System.out.println(e);
return;
}
finally {
System.out.println("End Program");
}
}
}
Previous programs had only one thread. This thread starts processing from the main method and executes statements in order from the top. This thread is called the main thread. This is called a single-threaded program, but it is also possible to create a program that executes two or more instructions at the same time. This is called a multithreaded program. An image in which there are two or more program processing flows, each of which progresses in parallel.
The following is a program that transfers 10,000 yen per person to a bank account and displays the total amount of money for 100 people. In order to execute a multithreaded program, it is necessary to inherit the Thread class and override the run method to define the specified process. If you create an instance of Thread class in the main method and call the start method, you can finally execute it.
In addition, exclusive control is performed by adding the syncronized qualifier to the join method to wait for the thread processing to finish, and to the addOneYen method so that only one thread can be executed at a time.
Multithreaded example
class Bank{
static int money=0;
static synchronized void addOneYen() {
money++;
};
}
class Customer extends Thread {
public void run() {
for(int i=0;i<10000;i++) {
Bank.addOneYen();
}
}
}
public class test4 {
public static void main(String[] arg) {
Customer[] customer=new Customer[100];
for ( int i=0;i<100;i++) {
customer[i]=new Customer();
customer[i].start();
}
for(int i=0;i<100;i++) {
try {
customer[i].join();
}catch(InterruptedException e) {
System.out.println(e);
}
}
System.out.println(Bank.money);
}
}
Recommended Posts