幾個關(guān)于java線程的demo郁竟,持續(xù)更新

1.生產(chǎn)者玛迄,消費(fèi)者線程。

 package com.test;

/**
 * Created by ll on 2017/10/6.
 */
public class PC {
public static void main(String[] args) {
    Shared shared=new Shared();
    new Producer(shared).start();
    new Consumer(shared).start();
}
}

class Shared {
private char c;
private volatile boolean writeable = true;

synchronized void setSharedChar(char c) {
    while (!writeable) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
        this.c = c;
        writeable = false;
        notify();

}

synchronized char getSharedChar() {
    while (writeable) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
        writeable = true;
        notify();
        return c;
}
}

class Producer extends Thread{
private final Shared shared;

Producer(Shared shared) {
    this.shared = shared;
}

@Override
public void run() {
    super.run();
    for (char  ch = 'A'; ch <='Z'; ch++) {
        synchronized (shared){
            shared.setSharedChar(ch);
            System.out.println(ch+"produced by produced");
        }
    }
}
}

class Consumer extends Thread{
private final Shared shared;

Consumer(Shared shared) {
    this.shared = shared;
}

@Override
public void run() {
    super.run();
    char ch;
    do {
        synchronized (shared){
            ch= shared.getSharedChar();
            System.out.println(ch+"consumed by consumer.");
        }

    } while (ch!='Z');
}
}

改進(jìn):

package com.test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by ll on 2017/10/6.
 */
public class PC {
public static void main(String[] args) {
    Shared shared=new Shared();
    new Producer(shared).start();
    new Consumer(shared).start();
}
}

class Shared {
private char c;
private volatile boolean available;

private final Lock lock;
private final Condition condition;

Shared() {
    available=false;
    lock=new ReentrantLock();
    condition=lock.newCondition();
}

Lock getLock(){
    return lock;
}

 void setSharedChar(char c) {
    lock.lock();

     try {
         while (available)
             try {
                 condition.await();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }

         this.c = c;
         available = true;
         condition.signal();
     } finally {
            lock.unlock();
     }

 }

 char getSharedChar() {
    lock.lock();
     
     try {
         while (!available)
             try {
                 condition.await();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }

         available = false;
         condition.signal();//喚醒一個等待中的線程
     } finally {
         lock.unlock();
         return c;
     }
 }
}

  class Producer extends Thread{
private final Shared shared;
private final Lock l;

Producer(Shared shared) {
    this.shared = shared;
    l=shared.getLock();
}

@Override
public void run() {
    super.run();
    for (char  ch = 'A'; ch <='Z'; ch++) {

            l.lock();
            shared.setSharedChar(ch);
            System.out.println(ch+"produced by produced");
            l.unlock();

    }
}
}

class Consumer extends Thread{
private final Shared shared;
private final Lock l;

Consumer(Shared shared) {
    this.shared = shared;
    l=shared.getLock();
}

@Override
public void run() {
    super.run();
    char ch;
    do {
            l.lock();
            ch= shared.getSharedChar();
            System.out.println(ch+"consumed by consumer.");
            l.unlock();

    } while (ch!='Z');
}
}

再次改進(jìn):

  package com.ll.test;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by ll on 2017/10/6.
*/
public class PC {
    public static void main(String[] args) {

    final BlockingQueue<Character> bq;
    bq= new ArrayBlockingQueue<Character>(26);

    final ExecutorService executorService= Executors.newFixedThreadPool(2);
    Runnable producer=()->{
        for (char ch='A';ch<='Z';ch++){
            try {
                bq.put(ch);
                System.out.println("produced by producer."+ch);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    executorService.execute(producer);

    Runnable consumer=()->{

        char ch='\0';

        do {
            try {
                ch=bq.take();
                System.out.println("consumerd by consumer."+ch);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (ch!='Z');
        executorService.shutdownNow();

    };
    executorService.execute(consumer);
    }
    }

注意:Fork/Join框架棚亩。

2.ThreadLocal蓖议。

public class ThreadLoclDemo {

private static volatile ThreadLocal<String> uid=new ThreadLocal<>();

public static void main(String[] args) {
    Runnable runnable=()->{
        String name=Thread.currentThread().getName();
        if (name.equals("A")){
            uid.set("AThread");
        }else{
            uid.set("otherThread");
        }
        System.out.println(name+" "+uid.get());
    };

    Thread thdA=new Thread(runnable);
    thdA.setName("A");
    Thread thdB=new Thread(runnable);
    thdB.setName("B");
    thdA.start();
    thdB.start();
}
}

3.InheritableThreadLocal。

public class ThreadThanfer {
private static final InheritableThreadLocal<Integer> inVal=new InheritableThreadLocal<>();

public static void main(String[] args) {
    Runnable runnable=()->{
      inVal.set(new Integer(100));
      Runnable runnable1=()->{
          Thread thd=Thread.currentThread();
          String name=thd.getName();
          System.out.println(name+":"+inVal.get());
        };
      Thread thdChild=new Thread(runnable1);
      thdChild.setName("Child");
      thdChild.start();
    };

    new Thread(runnable).start();
}

}

4.Executor讥蟆。

public class ExecutorTest {
public static void main(String[] args) {
    Runnable runnable=()->{
        String name=Thread.currentThread().getName();
        int count=0;
        while (true)
            System.out.println(name+" "+count++);
    };
    ExecutorService ex= Executors.newFixedThreadPool(2);
    ex.submit(runnable);
    ex.submit(runnable);

}
}

改進(jìn):

  public class ExecutorTest {
public static void main(String[] args) {
    Runnable runnable=()->{
        String name=Thread.currentThread().getName();
        int count=0;
        while (true)
            System.out.println(name+" "+count++);
    };
   /* ExecutorService ex= Executors.newFixedThreadPool(2);
    ex.submit(runnable);
    ex.submit(runnable);*/
   ExecutorService es=Executors.newSingleThreadExecutor(new NamedThread("A"));
   es.submit(runnable);
     es=Executors.newSingleThreadExecutor(new NamedThread("B"));
    es.submit(runnable);

}
}

class NamedThread implements ThreadFactory{

private volatile String name;

public NamedThread(String name) {
    this.name = name;
}

@Override
public Thread newThread(Runnable r) {
    return new Thread(r,name);
}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末勒虾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子瘸彤,更是在濱河造成了極大的恐慌修然,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件质况,死亡現(xiàn)場離奇詭異愕宋,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)结榄,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進(jìn)店門中贝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人臼朗,你說我怎么就攤上這事邻寿⌒粒” “怎么了?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵绣否,是天一觀的道長誊涯。 經(jīng)常有香客問我,道長蒜撮,這世上最難降的妖魔是什么暴构? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮淀弹,結(jié)果婚禮上丹壕,老公的妹妹穿的比我還像新娘庆械。我一直安慰自己薇溃,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布缭乘。 她就那樣靜靜地躺著沐序,像睡著了一般。 火紅的嫁衣襯著肌膚如雪堕绩。 梳的紋絲不亂的頭發(fā)上策幼,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天,我揣著相機(jī)與錄音奴紧,去河邊找鬼特姐。 笑死,一個胖子當(dāng)著我的面吹牛黍氮,可吹牛的內(nèi)容都是我干的唐含。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼沫浆,長吁一口氣:“原來是場噩夢啊……” “哼捷枯!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起专执,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤淮捆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后本股,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體攀痊,經(jīng)...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年拄显,在試婚紗的時候發(fā)現(xiàn)自己被綠了苟径。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡凿叠,死狀恐怖涩笤,靈堂內(nèi)的尸體忽然破棺而出嚼吞,到底是詐尸還是另有隱情,我是刑警寧澤蹬碧,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布舱禽,位于F島的核電站,受9級特大地震影響恩沽,放射性物質(zhì)發(fā)生泄漏誊稚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一罗心、第九天 我趴在偏房一處隱蔽的房頂上張望里伯。 院中可真熱鬧,春花似錦渤闷、人聲如沸疾瓮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽狼电。三九已至,卻和暖如春弦蹂,著一層夾襖步出監(jiān)牢的瞬間肩碟,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工凸椿, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留削祈,地道東北人。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓脑漫,卻偏偏與公主長得像髓抑,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子窿撬,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評論 2 354

推薦閱讀更多精彩內(nèi)容