Java 학습의 길 - (이상, 다중 스레드)
21988 단어 java 학습 기록
/*
throw:
: throws
: , new Exception
:throw new xxxException(" ")
*/
public class DemoThrow{
pubulic static void main() {
int[] arr = null;
getElement(arr, 0);
}
public static int getElement(int[] arr, int index) {
if(arr==null){
throw new NullPointerException(" ");
}
if()index < 0 || index >= arr.length) {
throw new ArrayIndexOutOfBoundsException();
}
int ele = arr[index];
return ele;
// Objects ,
Objects.requireNonNull(obj, " ");
}
}
/*
throws:
:
: ( ) throws AAAException,BBBException,...{
}
: , JVM
*/
public class Demothrows{
public static void main(String[] args) throws FileNotFoundException{
readFile();
}
public static void readFile(String path) throws FileNotFoundException {
if (!path.equals("D:\\\\test.txt")){
throw new FileNotFoundException();
}
}
}
/*
try..catch:
*/
public class DemoException{
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]);
}catch(Exception e){
System.out.println(e);
}
}
}
/*
finally
*/
public class DemoException{
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[3]);
}catch(Exception e){
System.out.println(e);
}finally{
System.out.println(" , , ");
}
}
}
/*
Exception RuntimeException
*/
public DemoException extends Exception{
//
public DemoException(){
super();
}
//
public DemeException(String msg){
super(msg);
}
}
다중 스레드
/*
java
Thread :
1.String getName()
2.static Thread currentThread()
3.void setName()
4.static void sleep(Long millis) xxx
*/
// 1. Runnable
public class RunnableImpl implements Runnable{
// 2. Runnable run ,
@override
public void run() {
for (int i=0; i<10000; i++) {
System.out.println(Thread.currentThread().getName() + "---" + i);
}
}
}
public class ThreadDemo{
public static void main(String[] args){
// 3. RunnableImpl
RunnableImpl demo = new RunnableImpl();
// 4. Thread , Runnable
Thread t = new Thread(demo);
// 5. thread start , Runnable run
t.start();
// main
for (int i = 0; i < 1000; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
}
}
}
/*
:
, , ,
, ,
:
new / () {
/
}
*/
public class InnerClassThreadDemo {
public static void main(String[] args){
//
new Thread(){
@override
public void run() {
for (int i = 0; i<20; i++) {
System.out.println(n);
}
}
}.start();
// Runnable
Runnable r = new Runnable() {
@override
public void run() {
for ...
}
}
new Thread(r).start();
//
new Thread(new Runnable() {
@override
public void run() {
for ...
}
}).start;
}
}