public static void main(String[] args) { // main thread 실행
...
}
public static void main(String[] args) {
Thread userTread =
new Thread(
() -> {
try {
Thread.sleep(3000);
System.out.println("UserThread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("MainThread finished");
}
// MainThread finished
// UserThread finished
public static void main(String[] args) {
Thread daemonThread =
new Thread(
() -> {
try {
Thread.sleep(3000);
System.out.println("DaemonThread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
daemonThread.setDaemon(true);
daemonThread.start();
System.out.println("MainThread finished");
}
// MainThread finished
public class MultiThread {
static class MyThread extends Thread{
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("extended userThread is finished");
}
}
public static void main(String[] args){
Runnable runnable =
new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("runnable userThread is finished");
}
};
Thread thread = new Thread(runnable);
thread.start(); // implement ruunable interface
MyThread myThread = new MyThread();
myThread.start(); // extend Thread class
System.out.println("mainThread is finished");
}
}
Thread thread = new Thread(() -> {
try {
Thread.sleep(3000);
System.out.println("UserThread finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
myThread.setPriority(1); // 1 ~ 10값을 줌. 높을수록 실행 기회를 더 많이 가짐. 상수로 설정 권
public class PriorityThread {
public static void main(String[] args){
Thread thread = new Thread(() -> {
for(int i = 0; i < 50; i++) {
System.out.println("priority1 thread running.");
}
});
Thread thread2 = new Thread(() -> {
for(int i = 0; i < 50; i++) {
System.out.println("priority10 thread running.");
}
});
thread.setPriority(1);
thread2.setPriority(10);
thread.start();
thread2.start();
System.out.println("mainThread is finished");
}
}
// 출력결과를 보면 thread1이 실행되다가 thread2가 실행되면 thread2를 우선적으로 처리하고 thread1이 마무리가 됌
// priority1 thread running.
// priority1 thread running.
// priority1 thread running.
// priority1 thread running.
// priority10 thread running.
// priority10 thread running.
// priority10 thread running.
// priority10 thread running.
...
// mainThread is finished
// priority1 thread running.
...
public sysnchronized void method() {
// 임계 영역
}
public void method() {
// 공유 영역
synchronized(공유 객체) {
// 임계 영역
}
// 공유 영역
}
public synchronized void setMemory(int memory) {
this.memory = memory;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(Thread.cuurentThread().getName() + " " + this.memory);
}
public void setMemory(int memory) {
synchronized (this) {
this.memory = memory;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
System.out.println(Thread.cuurentThread().getName() + " " + this.memory);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
interrupt(1000);
}
public void run() {
while (true) {
if (work) {
System.out.println("TrheadA 작업 내용");
} else {
Thread.yield();
}
}
}
public class JoinExample {
public static void main(String[] args) {
SumThread sumThread = new SumThread();
sumThread.start();
try {
sumThread.join();
} catch (InterruptedException e) {}
}
}
public class WorkObject {
public synchronized void methodA() {
notify();
try {
wait();
} catch (InterruptedExcpetion e) {}
}
public synchronized void methodB() {
notifiy();
try {
wait();
} catch (InterruptedException e) {}
}
}
public class ThreadA extends Thread {
private WorkObject workObject;
// 공유 객체를 매개값으로 받아 필드에 저장
public ThreadA(WorkObject workObject) {
this.workObject = workObject;
}
@Override
public void run() {
workObject.methodA();
}
}
public class ThreadB extends Thread { ... }
public static void main(String[] args) {
WorkObject sharedObject = new WorkObject();
ThreadA threadA = new ThreadA(sharedObject);
TrehadB threadB = new TrehadB(sharedObject);
threadA.start();
threadB.start();
// 번갈아 가며 실행
}
wai(), notify(), notifyAll()은 Object 클래스의 메소드이고, 그 이외는 Thread 클래스의 메소드들이다.
TrheadGroup group = Thread.currentThread().getThreadGroup();
String groupName = group.getName();
Map<Trehad, StackTraceElement[]> map = Thread.getAllStackTraces();
ThreadGroup tg = new ThreadGroup(string name);
ThreadGroup tg = new ThreadGroup(ThreadGroup parent, string name);
Thread t = new Thread(ThreadGroup group, Runnable target);
Thread t = new Thread(ThreadGroup group, Runnable target, String name);
Thread t = new Thread(ThreadGroup group, Runnable target, String name, long stackSize);
Thread t = new Thread(ThreadGroup group, String name);
ExecutorService executorService = Executors.newCachedTrheadPool();
// CPU 코어 개수만큼 스레드 생성
ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
ExecutorService ThreadPool = new ThreadPoolExecutor(
3, // 코어 스레드 개수
100, // 최대 스레드 개수
120L, // 놀고 있는 시간
TimeUnit.SECONDS, /// 놀고 있는 시간 단위
new SynchronousQueue<Runnable> // 작업 큐
);
일반적으로 남아있는 작업을 마무리하고 종료할 때는 shutdown(), 남아있는 작업과는 상관없이 강제로 종료할 때는 shutdownNow()를 호출한다.
Runnable task = new Runnable() {
@Override
public void run() {
// 작업
}
}
Callbale<T> task = new Callable<T>() {
@Override
public T call() throws Exception {
// 작업
return T;
}
}
execute()는 작업 처리 도중 예외가 발생하면 스레드가 종료되고 해당 스레드는 스레드 풀에서 제거되는 반면, submit()은 작업 처리 도중 예외가 발생하더라도 스레드는 종료되지 않고 다음 작업을 위해 재사용된다.
Future future = executorService.submit(task);
Future<T> future = executorService.submit(task);
Result result = ...;
Runnable task = new Task(result);
Future<Result> future = executorService.submit(task, result);
result = future.get();
ExecutorService executorService = Executors.newFixedThreadPoll(
Runtime.getRuntime().availableProcessors();
);
CompletionService<V> completionService = new ExecutorCompletionService<V>(
executorService
);
completionService.submit(Callable<V> task);
completionService.submit(Runnable task, V result);
CompletionHandler<V, A> callback = new CompletionHandler<V, A>() {
@Override
public void completed(V result, A attachment) {}
@Override
public void failed(Throwable exc, A attachment) {}
}