如何實現Java多線性同步讀寫數據
作者:佚名
Java多線性同步時我們經常使用的一個技術,我們需要不斷的學習。下面我們就來看看如何使用Java多線性同步進行數據的讀和寫。
Java多線性同步進行是一個很重要的東西,我們不少的時候都需要用到這些代碼。但是有人還不能很好的進行讀寫同步的相關代碼編寫。下面我們就看看如何才能正確的進行Java多線性同步的編寫。
- public class SynTest ...{
- private String firstName, lastName;
- private synchronized String getName() ...{
- String result = firstName + " " + lastName;
- return result;
- }
- private synchronized void setName(String firstName,
String lastName) ...{- print("entering setName");
- this.firstName = firstName;
- print("Set first name have done firstName=" +
this.firstName);- try ...{
- Thread.sleep(1000);
- } catch (InterruptedException e) ...{
- }
- this.lastName = lastName;
- print("set last name have done,and leave setName()
method.firstName="- + this.firstName + " lastName=" + this.lastName);
- }
- private static void print(String msg) ...{
- String thread = Thread.currentThread().getName();
- System.out.println(thread + ": " + msg);
- }
- public static void main(String[] args) ...{
- // 必需聲明為final,否則runnable里面的run()方法不能訪問。
- final SynTest test1 = new SynTest();
- // 設置初始值
- test1.setName("arzu", "guli");
- Runnable run1 = new Runnable() ...{
- public void run() ...{
- test1.setName("kang", "midi");
- }
- };
- // 修改名字線程
- Thread threadOne = new Thread(run1, "threadOne");
- threadOne.start();
- try ...{
- Thread.sleep(200);
- } catch (InterruptedException e) ...{
- }
- Runnable run2 = new Runnable() ...{
- public void run() ...{
- print("讀取" + test1.getName());
- }
- };
- // 讀取名字線程
- Thread threadTwo = new Thread(run2, "threadTwo");
- threadTwo.start();
- System.out.println("main() exit");
- }
- }
以上就是對Java多線性同步的詳細介紹。
【編輯推薦】
責任編輯:張浩
來源:
互聯網