Java多線程如何解決關(guān)鍵字封鎖問題
Java多線程需要我們不斷的進(jìn)行完善,相關(guān)的技術(shù)如何才能更好的使用,在這個(gè)問題上不少開發(fā)者和使用者都很關(guān)心。下面我們先來看看如何才能更好的學(xué)習(xí)Java多線程的使用方法。
實(shí)例方法中加入sychronized關(guān)鍵字封鎖的是this對(duì)象本身,而在靜態(tài)方法中加入sychronized關(guān)鍵字封鎖的就是類本身。靜態(tài)方法是所有類實(shí)例對(duì)象所共享的,因此Java多線程對(duì)象在訪問此靜態(tài)方法時(shí)是互斥訪問的,從而可以實(shí)現(xiàn)線程的同步,代碼如下所示:
代碼
- package com.vista;
- class MyThread implements java.lang.Runnable
- {
- private int threadId;
- public MyThread(int id)
- {
- this.threadId = id;
- }
- @Override
- public void run()
- {
- taskHandler(this.threadId);
- }
- private static synchronized void taskHandler(int threadId)
- {
- for (int i = 0; i < 100; ++i)
- {
- System.out.println("Thread ID: " + threadId + " : " + i);
- }
- }
- }
- public class ThreadDemo
- {
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException
- {
- for (int i = 0; i < 10; ++i)
- {
- new Thread(new MyThread(i)).start();
- Thread.sleep(1);
- }
- }
- }
以上就是對(duì)Java多線程的詳細(xì)介紹,希望大家有所收獲。
【編輯推薦】