public void run()
을 오버라이드하고 public void start()
를 통해 스레드를 생성 및 실행한다.Threads are represented by the Thread class. The only way for a user to create a thread is to create an object of this class; each thread is associated with such an object. A thread will start when the start() method is invoked on the corresponding Thread object.
public class PrimeThread extends Thread {
private int num;
private int prime;
public PrimeThread(int num) {
this.num = num;
}
public int getPrime() {
return prime;
}
@Override
public void run() {
int p = num;
while(!isPrime(p)) {
p++;
}
prime = p;
}
public static void main(String[] args) {
PrimeThread p = new PrimeThread(5000);
p.start();
try {
p.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(p.getPrime());
}
private boolean isPrime(int n) {
if (n <= 2) return false;
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
public class FindPrime implements Runnable{
private int num;
private int prime;
//생략
public static void main(String[] args) {
FindPrime p = new FindPrime(9030);
Thread t = new Thread(p);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(p.getPrime());
}
}
static void sleep(long mills) //현재 스레드를 멈춤
void join()
void join(long mills) //대기 시간 지정 가능
void inturrupt() //WAITING -> RUNNABLE
void stop() // 즉시 종료
void suspend() //일시 종료,
void resume() //suspend -> resume
static void yield() //실행권을 양보함
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println(t.getName());
System.out.println(t.getThreadGroup().getName());
System.out.println(t.getPriority());
}
synchronized
사용. synchronized
를 사용하면 객체의 참조를 를 보고 락 상태라면 실행을 멈춘다.a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.
The synchronized statement (§14.19) computes a reference to an object; it then attempts to perform a lock action on that object's monitor and does not proceed further until the lock action has successfully completed. After the lock action has been performed, the body of the synchronized statement is executed. If execution of the body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.
A synchronized method (§8.4.3.6) automatically performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed. If the method is an instance method, it locks the monitor associated with the instance for which it was invoked (that is, the object that will be known as this during execution of the body of the method). If the method is static, it locks the monitor associated with the Class object that represents the class in which the method is defined. If execution of the method's body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same monitor.
void synchronized foo() {
//critical code here
}
void foo2() {
Info a;
synchronized(a) {
//critical code here
}
package net.honux;
public class SumTest extends Thread {
private static Info sum;
private long curr;
private long start;
private long end;
public SumTest(long start, long end, String name) {
this.start = start;
this.curr = start;
this.end = end;
System.out.println(start + " to " + end);
this.setName(name);
sum = new Info(0);
}
@Override
public void run() {
calc();
}
private synchronized void calc() {
for (long i = start; i <= end; i++) {
sum.add(i);
}
System.out.println(this.getName() + " ended");
}
public static void main(String[] args) {
long l = 10000L;
final int NUM_THREAD = 5;
long step = l / NUM_THREAD;
SumTest[] t = new SumTest[NUM_THREAD];
for (int i = 0; i < 5; i++) {
t[i] = new SumTest(i * step + 1, (i + 1) * step, "T" + i);
}
for (var curr : t) {
curr.start();
}
try {
for (var curr : t) {
curr.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum);
}
}
class Info {
public long value;
Info(long v) {
this.value = v;
}
public void add(long v) {
value += v;
}
@Override
public String toString() {
return "Info{" +
"value=" + value +
'}';
}
}
private void calc() {
for (long i = start; i <= end; i++) {
synchronized (sum) {
sum.add(i);
}
}
System.out.println(this.getName() + " ended");
}
/* 수정된 calc() 메소드
private void calc() {
for (long i = start; i <= end; i++) {
sum.add(i);
}
System.out.println(this.getName() + " ended");
}*/
class Info {
public long value;
Info(long v) {
this.value = v;
}
public synchronized void add(long v) {
value += v;
}
@Override
public String toString() {
return "Info{" +
"value=" + value +
'}';
}
}