자바 스 레 드 초기 화

자바 스 레 드 초기 화
 
 
http://chuhanzhi.com/?p=66  링크 를 클릭 하여 정 리 된 글 을 보다
스 레 드 만 드 는 두 가지 방법:
1.       Thread 클래스 를 계승 하고 run 방법 은 다음 과 같 습 니 다.
 
package thread;
 
public class FirstThread extends Thread {//      Thread  

    @Override
    public void run() {
        while (true) {
            System.out.println(1);
            System.out.println(this.getName());
        }
    }
 
    public static void main(String[] args) {
        FirstThread th = new FirstThread();
        th.setName("th1");
        th.start();
        Thread th2=new Thread(new SecondThread(),"th2");
        Thread th3 =new Thread(th2,"th3");//    Thread       Runnable      Thread      Thread                
        th2.start();
        th3.start();
    }
}

 
 
2.       Rannable 을 실현 하면 스 레 드 가 다른 종류의 인 터 페 이 스 를 다음 과 같이 계승 할 수 있 습 니 다.
 
package thread;

 

public class SecondThread implements Runnable {

    @Override

    public void run() {

        while (true) {

            System.out.println("2");

            System.out.println(Thread.currentThread().getName());

        }

    }

} 

 
스 레 드 정지:
1.       스 레 드 가 정상적으로 끝 났 을 때 종료 할 수 있 습 니 다. First Thread 에서 run 방법 은 실행 이 끝 난 후에 자동 으로 종료 할 수 있 습 니 다.
 
  public void run() {

            System.out.println(1);

            System.out.println(this.getName());

    }

  

  
2.       스 레 드 정지 표시 사용 하기
 
package thread;

 

import java.util.concurrent.BlockingQueue;

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class FlagStopThread extends Thread {

    public volatile boolean exit = false;

    @Override

    public void run() {

        while (!exit) {

            System.out.println("111111111");//                 ,       put   ,            ,      exit        ,          

                                             //           ,                  

        }

//        BlockingQueue queue = null;//                

//        boolean interrupt=false;

//        while(true){

//            try {

//                queue.take();

//             } catch (InterruptedException ex) {

//                interrupt=true;

//            }finally{

//                if(interrupt){

//                    Thread.currentThread().interrupt();

//                }

//            }

//        }

    }

 

    public static void main(String[] args) throws InterruptedException {

        FlagStopThread stopThread = new FlagStopThread();

        stopThread.start();

        sleep(1000);//      

        stopThread.exit = true;

        System.out.println("stop.........");

        //stopThread.join();

    }

} 

 
3.       interrupt 사용 정지
 
package thread;

 

public class InterruptStopThread extends Thread {

    //    interrupt     

 

    /**

     * interrupt          

     * isInterrupted         

     * interrupted                ,                false ,           ,

     *         false (                        )

     */

    @Override

    public void run() {

        while (!Thread.currentThread().isInterrupted()) {

            try {

                System.out.println("11111111111" + this.isInterrupted());

                 sleep(1000);//   sleep      interrupt           true , sleep                ,

                            //             catch   ,         false (    sleep          )

            } catch (InterruptedException ex) {

                /**

                 *                  ,                        。

                 */

                System.out.println(this.isInterrupted()+"        ");

                this.interrupt();//           true   while     ,     //      try    while 

               

            } finally {

            }

        }

    }

 

    public static void main(String[] args) throws InterruptedException {

        InterruptStopThread interruptStopThread = new InterruptStopThread();

        interruptStopThread.start();

        sleep(1000);

        interruptStopThread.interrupt();

         System.out.println(interruptStopThread.isInterrupted()+"5555");

    }

} 

 
4.       스 톱 등 추천 하지 않 는 방법 도 있어 요.
추천 하지 않 으 면 깊이 연구 하지 않 는 다.
sleep join wait notify 방법
wait 방법:
 
package thread;

 

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class SleepThread extends Thread {

 

    @Override

    public void run() {

        try {

            while (true) {

                System.out.println("1111111111...");

                 sleep(1000);//sleep        ,                                 java                      

                //suspend();        ,     

                //resume();

            }

 

        } catch (InterruptedException ex) {//     run        throws        try{}catch(){},           interrupt      sleep       InterruptedException   

            System.out.println("111");

        }

    }

 

    public static void main(String[] args) {

        SleepThread sleepThread = new SleepThread();

        sleepThread.start();

    }

} 

 
join 방법
 
 
 
 
package thread;

 

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class JoinThread extends Thread {

 

    /**

     *             volatile ,               。        。        synchronized    

     *

     * Java                  。

     *         Java       。    ,      new         ,           、           ,

     *   Jointhread     n         。             。                  ,

     *            run      run               ,       。

     *                ,           ,                   ,

     *      ,                    。     n++       

     */

    public volatile static int n = 0;

 

    @Override

    public void run() {

        for (int i = 0; i < 100; i++) {

            n = n + 1;

            try {

                sleep(1000);//    n=n+1        。        ,      

            } catch (InterruptedException ex) {

                Logger.getLogger(JoinThread.class.getName()).log(Level.SEVERE, null, ex);

            }

            System.out.println(Thread.currentThread().getName() + "  n=" + n);

        }

 

    }

 

    public static void main(String[] args) {

        JoinThread[] joinThreads = new JoinThread[3];

        for (int i = 0; i < joinThreads.length; i++) {

             joinThreads[i] = new JoinThread();

        }

        for (int i = 0; i < joinThreads.length; i++) {

            joinThreads[i].setName("thread" + i);

            joinThreads[i].start();

//            try {

//                joinThreads[i].join();

//            } catch (InterruptedException ex) {

//                Logger.getLogger(JoinThread.class.getName()).log(Level.SEVERE, null, ex);

//            }

        }

        System.out.println("n=" + n);

    }

}

  

 
 
 
synchronized
 
package thread;

//http://stackoverflow.com/questions/437620/java-synchronized-methods-lock-on-object-or-class/437627#437627

public class Synchronized1Thread implements Runnable {

 

    public String methodName;

//    public synchronized void method1() {

//        while (true) {

//            System.out.println("1111111" + Thread.currentThread().getName() + "   " + methodName);

//

//        }

//    }

//method1            

    public  void method1() {

        synchronized (this) {

            while (true) {

                System.out.println("1111111" + Thread.currentThread().getName() + "   " + methodName);

 

            }

        }

 

    }

 

    public synchronized void method2() {

        while (true) {

            System.out.println("2222222");

        }

     }

 

    public static synchronized void method3() {

        while (true) {

            System.out.println("3333333" + Thread.currentThread().getName());

        }

    }

//method3        

//    public static  void method3() throws ClassNotFoundException {

//        synchronized (Class.forName("Synchronized1Thread")) {

//            while (true) {

//                System.out.println("3333333" + Thread.currentThread().getName());

//            }

//        }

//    }

 

    public static synchronized void method4() {

        while (true) {

            System.out.println("4444444");

        }

    }

 

    @Override

    public void run() {

        try {

            this.getClass().getMethod(methodName).invoke(this);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    public static void main(String[] args) throws InterruptedException {

        /*

         *    synchronized           (   )

         *               

         *         synchronized           Class                                 ,

         *                 (                ,            Class   )

         */

        Synchronized1Thread syn1 = new Synchronized1Thread();

        Synchronized1Thread syn2 = new Synchronized1Thread();

        syn1.methodName = "method1";

        syn2.methodName = "method4";

        new Thread(syn1).start();

        Thread.sleep(100);//                      run     

        new Thread(syn2).start();//1 1 (             ), 1 2 , 1 3      ,  3 3 , 3 4       ( 1 1           method1   method1       )

 

//        Synchronized1Thread syn1 = new Synchronized1Thread();

//        syn1.methodName = "method1";

//        new Thread(syn1).start();

//        Thread.sleep(100);

//        syn1.methodName = "method3";

//

//        new Thread(syn1).start();;//1 2 , 1 1       , 1 3                  

 

 

    }

}


 
 
 
wait 방법
package thread;

 

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class WaitThread {

    /*

     * wait          sleep join    ,                          。

     *     notify   notifyAll                。

     *     notify                      wait          notify                  ,     notifyAll

     *         wait()         ,           。

     *          notify()              wait()                     (              )

     *                  wait        synchronized ,   synchronized              ,       

     */

 

    public static void main(String[] args) {

        NotifyThread notifyThread = new NotifyThread();

        System.out.println("result is coming soon...");

        notifyThread.start();

//        try {//                notify        wait    ,       wait   notify             

//            Thread.sleep(1000);

//        } catch (InterruptedException ex) {

//            Logger.getLogger(WaitThread.class.getName()).log(Level.SEVERE, null, ex);

//        }

        synchronized (notifyThread) {

            try {

                notifyThread.wait();

                //notifyThread.wait();//              wait              wait      ,                         

            } catch (InterruptedException ex) {

                Logger.getLogger(WaitThread.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

        System.out.println("result is:" + notifyThread.a);

    }

}

 

class NotifyThread extends Thread {

 

    public Integer a = 0;

 

    @Override

    public void run() {

        synchronized (this) {

            for (int i = 0; i < 101; i++) {

                a = a + i;

            }

            notify();

        }

    }

} 

 
생산자 소비자
 
package thread;

 

import java.util.Random;

import java.util.logging.Level;

import java.util.logging.Logger;

 

public class CustomerProducterThread {

 

    public static void main(String[] args) {

        Storage storage = new Storage();

        Customer c1 = new Customer(storage);

        c1.setName("c1");

        Customer c2 = new Customer(storage);

        c2.setName("c2");

        Customer c3 = new Customer(storage);

        c3.setName("c3");

        Customer c4 = new Customer(storage);

        c4.setName("c4");

        Producter p1 = new Producter(storage);

        p1.setName("p1");

        Producter p2 = new Producter(storage);

        p2.setName("p2");

        Producter p3 = new Producter(storage);

        p3.setName("p3");

        Producter p4 = new Producter(storage);

        p4.setName("p4");

        c1.start();

        c2.start();

        p1.start();

        p2.start();

        p3.start();

        p4.start();

        c3.start();

        c4.start();

 

    }

}

 

class Storage {//   

 

    public static final int[] lock = new int[0];

    public static final Integer max = 100;

    private Integer sto = 0;

 

    public void put(int i, String name) {//     

        synchronized (lock) {

            if ((this.sto + i) > max) {

                System.out.println(name + "      ............" + i);

                try {

                    lock.wait();

                    put(i,name);//   wait         put            i     ,              ,      

                } catch (InterruptedException ex) {

                     Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);

                }

            } else {

                this.sto = this.sto + i;

                System.out.println(name + "     " + i + "    ,      " + this.sto);

                lock.notifyAll();

            }

        }

    }

 

    public void get(int i, String name) {//     

        synchronized (lock) {

            if (this.sto - i < 0) {

                System.out.println(name + "        ............" + i);

                 try {

                    lock.wait();

                    get(i,name);

                } catch (InterruptedException ex) {

                    Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);

                }

            } else {

                this.sto = this.sto - i;

                System.out.println(name + "     " + i + "    ,      " + this.sto);

                lock.notifyAll();

            }

 

 

        }

    }

}

 

class Customer extends Thread {//    

 

    public Storage sto;

 

    public Customer(Storage sto) {

        this.sto = sto;

    }

 

    @Override

    public void run() {

        while (true) {

            sto.get(new Random().nextInt(10) + 1, Thread.currentThread().getName());

        }

 

    }

}

 

class Producter extends Thread {//    

 

    public Storage sto;

 

    public Producter(Storage sto) {

        this.sto = sto;

    }

 

    @Override

    public void run() {

        while (true) {

            sto.put(new Random().nextInt(10) + 1, Thread.currentThread().getName());

        }

 

    }

} 

 
 
Dead Lock 간단 한 인 스 턴 스
 
package thread;

 

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

 

public class LeftRightDeadLockThread {

 

    private Object left = new Object();

    private Object right = new Object();

 

    public void leftRight() {

        synchronized (left) {

            synchronized (right) {

                System.out.println("leftRight");

            }

        }

    }

 

    public void rightLeft() {

        synchronized (right) {

            synchronized (left) {

                System.out.println("rightLeft");

            }

        }

    }

    /*

     * A-    left-      right--     

     *  B-    right-      left--     

     */

 

    public static void main(String[] args) {

        final LeftRightDeadLockThread lRDLT = new LeftRightDeadLockThread();

        ExecutorService service = Executors.newFixedThreadPool(2);

        service.submit(new Runnable() {

 

            @Override

            public void run() {

                while (true) {

                    lRDLT.leftRight();

                }

            }

        });

        service.submit(new Runnable() {

 

            @Override

            public void run() {

                while (true) {

                    lRDLT.rightLeft();

                }

            }

        });

        service.shutdown();

    }

} 

  ThreadLocal:
//ThreadLocal get  
// public T get() {
//        Thread t = Thread.currentThread();
//        ThreadLocalMap map = getMap(t);//getMap(t)      return t.threadLocals;           ThreadLocalMap threadLocals  
//        if (map != null) {
//            ThreadLocalMap.Entry e = map.getEntry(this);//   map       ThreadLocal      key      
//            if (e != null)
//                return (T)e.value;
//        }
//        return setInitialValue();//  map         ThreadLocal      key map            
//    }
//setInitialValue()  
//private T setInitialValue() {
//        T value = initialValue();//initialValue()         ,      protected            ,                         ,           new                            
//        Thread t = Thread.currentThread();
//        ThreadLocalMap map = getMap(t);
//        if (map != null)
//            map.set(this, value);
//        else
//            createMap(t, value);
//        return value;
//    }
//set  
//public void set(T value) {
//        Thread t = Thread.currentThread();
//        ThreadLocalMap map = getMap(t);
//        if (map != null)
//            map.set(this, value);
//        else
//            createMap(t, value);
//    }
/**
 *       ThreadLocal set   get     :
 *  set  :
 * 1.           
 * 2.         ThreadLocalMap      
 * 3. ThreadLocal key      map   
 *    get  :
 * 1.           
 * 2.         ThreadLocalMap      
 * 3.map     ThreadLocalMap    ,              。
 *      map        initialValue     
 *          ,ThreadLocal set()                                 ThreadLocalMap  
 * get             ThreadLocalMap       ,            ThreadLocalMap         
 * 
 * ThreadLocal                     ,         :        “  ”             ,         
 *                  ,           ThreadLoca ,     session   
 */
package thread;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ThreadLocalThread {//           
//
//    ThreadLocal threadLocal = new ThreadLocal() {
//
//        protected synchronized Object initialValue() {
//            return new Integer(0);
//        }
//    };
    public static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static final ThreadLocal session =new ThreadLocal();

    public static Session currentSession() throws HibernateException {//               Session           
        Session s = (Session) session.get();
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s != null) {
            s.close();
        }
        session.set(null);
    }
}

 
 

좋은 웹페이지 즐겨찾기