public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); } } MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.start(); myThread2.start();
public class MyThread extends OtherClass implements Runnable { public void run() { System.out.println("MyThread.run()"); } }
public class CallableDemo implements Callable<String> { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService=Executors.newFixedThreadPool(1); CallableDemo callableDemo=new CallableDemo(); Future<String> future=executorService.submit(callableDemo); System.out.println(future.get()); executorService.shutdown(); } @Override public String call() throws Exception { int a=1; int b=2; System.out.println(a+b); return "执行结果:"+(a+b); } }
public class Request { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Request{" + "name=‘" + name + ‘\‘‘ +‘}‘; } }
public interface RequestProcessor { void processRequest(Request request); }
public class PrintProcessor extends Thread implements RequestProcessor{ LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<Request>(); private final RequestProcessor nextProcessor;
public PrintProcessor(RequestProcessor nextProcessor) { this.nextProcessor = nextProcessor; }
@Override public void run() { while (true) { try { Request request=requests.take(); System.out.println("print data:"+request.getName()); nextProcessor.processRequest(request); } catch (InterruptedException e) { e.printStackTrace(); } } } //处理请求 public void processRequest(Request request) { requests.add(request); } }
public class SaveProcessor extends Thread implements RequestProcessor{ LinkedBlockingQueue<Request> requests = new LinkedBlockingQueue<Request>(); @Override public void run() { while (true) { try { Request request=requests.take(); System.out.println("begin save request info:"+request); } catch (InterruptedException e) { e.printStackTrace(); } } } //处理请求 public void processRequest(Request request) { requests.add(request);
} }
public class Main { PrintProcessor printProcessor; protected Main(){ SaveProcessor saveProcessor=new SaveProcessor(); saveProcessor.start(); printProcessor=new PrintProcessor(saveProcessor); printProcessor.start(); } private void doTest(Request request){ printProcessor.processRequest(request); } public static void main(String[] args) { Request request=new Request();request.setName("Mic"); new Main().doTest(request); } }
public class ThreadStatus { public static void main(String[] args) { //TIME_WAITING new Thread(()->{ while(true){ try { TimeUnit.SECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } },"timewaiting").start(); //WAITING,线程在 ThreadStatus 类锁上通过 wait 进行等待 new Thread(()->{ while(true){ synchronized (ThreadStatus.class){ try { ThreadStatus.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } },"Waiting").start(); //线程在 ThreadStatus 加锁后,不会释放锁 new Thread(new BlockedDemo(),"BlockDemo-01").start(); new Thread(new BlockedDemo(),"BlockDemo-02").start(); } static class BlockedDemo extends Thread{ public void run(){ synchronized (BlockedDemo.class){ while(true){ try { TimeUnit.SECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } }
} } } }
static JNINativeMethod methods[] = { {"start0", "()V", (void *)&JVM_StartThread}, {"stop0", "(" OBJ ")V", (void *)&JVM_StopThread}, {"isAlive", "()Z", (void *)&JVM_IsThreadAlive}, {"suspend0", "()V", (void *)&JVM_SuspendThread}, {"resume0", "()V", (void *)&JVM_ResumeThread}, {"setPriority0", "(I)V", (void *)&JVM_SetThreadPriority}, {"yield", "()V", (void *)&JVM_Yield}, {"sleep", "(J)V", (void *)&JVM_Sleep}, {"currentThread", "()" THD, (void *)&JVM_CurrentThread}, {"countStackFrames", "()I", (void *)&JVM_CountStackFrames}, {"interrupt0", "()V", (void *)&JVM_Interrupt}, {"isInterrupted", "(Z)Z", (void *)&JVM_IsInterrupted}, {"holdsLock", "(" OBJ ")Z", (void *)&JVM_HoldsLock}, {"getThreads", "()[" THD, (void *)&JVM_GetAllThreads}, {"dumpThreads", "([" THD ")[[" STE, (void *)&JVM_DumpThreads}, }; #undef THD #undef OBJ #undef STE JNIEXPORT void JNICALL Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls) { (*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods)); }
JVM_ENTRY(void,JVM_StartThread(JNIEnv*env,jobject jthread)) JVMWrapper("JVM_StartThread"); ........ native_thread = new JavaThread(&thread_entry,sz); ......
JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : Thread() #if INCLUDE_ALL_GCS , _satb_mark_queue(&_satb_mark_queue_set), _dirty_card_queue(&_dirty_card_queue_set) #endif // INCLUDE_ALL_GCS { if (TraceThreadEvents) { tty->print_cr("creating thread %p", this); } initialize(); _jni_attach_state = _not_attaching_via_jni; set_entry_point(entry_point); // Create the native thread itself. // %note runtime_23 os::ThreadType thr_type = os::java_thread; thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : os::java_thread; os::create_thread(this, thr_type, stack_sz); _safepoint_visible = false; // The _osthread may be NULL here because we ran out of memory (too many threads active). // We need to throw and OutOfMemoryError - however we cannot do this here because the caller // may hold a lock and all locks must be unlocked before throwing the exception (throwing // the exception consists of creating the exception object & initializing it, initialization // will leave the VM via a JavaCall and then all locks must be unlocked). // // The thread is still suspended when we reach here. Thread must be explicit started // by creator! Furthermore, the thread must also explicitly be added to the Threads list // by calling Threads:add. The reason why this is not done here, is because the thread // object must be fully initialized (take a look at JVM_Start) }
void Thread::start(Thread* thread) { trace("start", thread); // Start is different from resume in that its safety is guaranteed by context or // being called from a Java method synchronized on the Thread object. if (!DisableStartThread) { if (thread->is_Java_thread()) { // Initialize the thread state to RUNNABLE before starting this thread. // Can not set it after the thread started because we do not know the // exact thread state at that time. It could be in MONITOR_WAIT or // in SLEEPING or some other state. java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), java_lang_Thread::RUNNABLE); } os::start_thread(thread); } }
public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException { Thread thread=new Thread(()->{ while(!Thread.currentThread().isInterrupted()){ //默认情况下isInterrupted 返回 false、通过 thread.interrupt 变成了 true i++; } System.out.println("Num:"+i); },"interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); //加和不加的效果
} }
public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException { Thread thread=new Thread(()->{ while(true){
if(Thread.currentThread().isInterrupted()){ System.out.println("before:"+Thread.currentThread().isInterrupted()); Thread.interrupted(); //对线程进行复位,由 true 变成 false System.out.println("after:"+Thread.currentThread().isInterrupted()); } } },"interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); } }
public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException{ Thread thread=new Thread(()->{ while(!Thread.currentThread().isInterrupted()){ i++; } System.out.println("Num:"+i); },"interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); System.out.println(th read.isInterrupted()); }
}
public class InterruptDemo { private static int i; public static void main(String[] args) throws InterruptedException { Thread thread=new Thread(()->{ while(!Thread.currentThread().isInterrupted()){ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
} System.out.println("Num:"+i); },"interruptDemo"); thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); System.out.println(th read.isInterrupted());
}
}
public void interrupt() { if (this != Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag b.interrupt(this); return; } } interrupt0(); }
JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread)) JVMWrapper("JVM_Interrupt"); // Ensure that the C++ Thread and OSThread structures aren‘t freed before we operate oop java_thread = JNIHandles::resolve_non_null(jthread); MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock); // We need to re-resolve the java_thread, since a GC might have happened during the // acquire of the lock JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)); if (thr != NULL) { Thread::interrupt(thr); } JVM_END
void Thread::interrupt(Thread* thread) { trace("interrupt", thread); debug_only(check_for_dangling_thread_pointer(thread);) os::interrupt(thread); }
JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis)) JVMWrapper("JVM_Sleep"); if (millis < 0) { THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); } // 判断并清除线程中断状态,如果中断状态为true,则抛出异常 if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) { THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted"); } // Save current thread state and restore it at the end of this block. // And set new thread state to SLEEPING. JavaThreadSleepState jtss(thread); ....
JVM_END
原文:https://www.cnblogs.com/qlsem/p/11468837.html