'Java'에 해당되는 글 84건

  1. 2015.01.14 Java Streams - Java Stream Introduction
  2. 2015.01.14 ShowThread
  3. 2015.01.14 Thread 3
  4. 2015.01.14 Thread 2
  5. 2015.01.14 an usage of Vector
  6. 2015.01.14 basic Vector
  7. 2015.01.13 encapsulating
  8. 2015.01.13 building a Stack structure
  9. 2015.01.12 ProcessBuilder
  10. 2015.01.06 UrlFrame, getting the page source and save as a txt file
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

A stream is a sequence of data values supporting sequential and parallel aggregate operations.


We use the aggregate functions in SQL more often. For example we can sum all sale figures for a month or a year. We can also get the max value for a give range.


An aggregate operation works on a list of item and results in a single value


The result of an aggregate operation on stream may be a primitive value., an object, or a void for Stream. Like SQL we can calculate sum for all integer in a stream of integers



Collections vs Streams


Java Collections focus on how to store data elements for efficient access.

Java streams focus on aggregate operations on data elements from a data source



Stream Features

Java Streams have its own features



No Storage

Java Streams have no storage

A collection is an in-memory data structure that stores all its elements


A stream has no storage. A stream pulls elements from a data source on-demand and passes them to a pipeline of operations for processing


For a collection we talk about the storage or how the data elements are stored, how to access data elements


For a stream we focus on the operations, for example, how to sum a stream



Infinite Streams

A collection cannot represent a group of infinite elements whereas a stream can.


A stream can pull its elements from a data sourve. The data source can be a collection, a function that generates data, an I/O channel, etc.


A stream can pull data from a function which generates infinite number of elements




Not Reusable

Streams Are Not Reusable


A stream cannot be reused after calling a terminal operation


To perform a computation on the same elements from the same data source, we have to recreate the stream pipeline


A stream may throw an IllegalStateException in case of reusing





'Java' 카테고리의 다른 글

Collections : swap ( List list, int i, int j )  (0) 2015.01.14
Collections : reverseOrder()  (0) 2015.01.14
ShowThread  (0) 2015.01.14
an usage of Vector  (0) 2015.01.14
basic Vector  (0) 2015.01.14
Posted by af334
2015. 1. 14. 19:56
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package Thread;

class ShowThread extends Thread{
    String threadName;
    public ShowThread(String name){
        threadName=name;
    }
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("안녕하세요."+threadName +"입니다");
            try {
                sleep(100);
            } catch (Exception e) {
                    e.printStackTrace();
            }
        }
    }
}

class Delay extends Thread{
    public void delay(){
        try{
            sleep(100);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
}

===================


package Thread;

public class ThreadUnderstand{
    public static void main(String[] args){
        ShowThread st1=new ShowThread("st1 스레드");
        ShowThread st2=new ShowThread("std2 스레드");
        Delay s=new Delay();
       
        st1.start(); //start()를 실행하면 run()메소드가 동작하도록 내부적으로 코딩되어 있다
        st2.start();
       
        System.out.println("순착적인 출력물1");
        s.delay();  //너무 빨리 실행 되어 딜레이를 걸어줌
        System.out.println("출력물2");
        System.out.println("출력물3");
        System.out.println("출력물4");
       
    }
}



'Java' 카테고리의 다른 글

Collections : reverseOrder()  (0) 2015.01.14
Java Streams - Java Stream Introduction  (0) 2015.01.14
an usage of Vector  (0) 2015.01.14
basic Vector  (0) 2015.01.14
encapsulating  (0) 2015.01.13
Posted by af334
2015. 1. 14. 03:06
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

일반적으로 분리된 스레드가 종료될 때까지 대기하기 위해 while문을 사용하여 반복문 내에서 분리된 스레드의 isAlive() 메소드를 사용해 스레드의 종료 여부를 확인한다. 하지만 join()메소드를 사용해 이런 대기 작업을 대신 할 수 있다.




-----------------------



package Thread;

public class JoinDemo {
    public static void main(String[] args){
        Runnable r=new Runnable() {
           
            @Override
            public void run() {
                System.out.println("Worker thread is simulating "+"work by sleeping for 5 seconds.");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ie) {
                }
                System.out.println("Worker thread is dying");
            }
        };
        Thread thd=new Thread(r);
        thd.start();
        System.out.println("Default main thread is doing work");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
        }
        System.out.println("Default main thread has finished its work");
        System.out.println("Default main therad is waiting for worker thread "+"to die");
       
        try {
            thd.join();
        } catch (InterruptedException ie) {
        }
        System.out.println("Main thread is dying");
    }
}


기본 메인 스레드에서 작업 스레드를 시작한 후 몇가지 작업을 처리하는데 작업 스레드의 thd객체를 통해 호출된 join()메소드에 의해 작업 스레드가 종료될 때까지 대기한다.


모든 Thread 객체는 ThreadGroup 객체에 고한다. Thread 클래스는 ThreadGroup 객체를 반환하는 ThreadGroup getThreadGroup() 메소드를 선언하고 있는데 ThreadGroup 객체는 거의 사용되지 않기 때문에 무시해도 된다. 만일 논리적인 Thread 객체 그룹이 필요하다면 배열 또는 콜렉션을 사용하여 그룹핑하는 것이 더 효율적이다.



***

ThreadGroup 클래스의 몇몇 메소드는 결함이 있다. 예를 들어 int enumerate(Thread[] threads) 메소드는 인자 threads의 배열이 Thread 객체들을 저장하기에 충분한 크기가 아닐 경우 모든 액티브 스레드를 포함하지 못한다. 배열의 정확한 크기를 알기 위해 int activeCount(); 메소드에서 반환하는 값을 사용할 수 있을 거라 생각할 수도 있지만 activeCount() 메소드의 반환값은 스레드의 생성과 종료에 따라 수시로 변동이 되기 때문에 반환된 값이 정확한 배열의 크기가 될 수 없는 경우가 많다.






'Java > Working-level Java' 카테고리의 다른 글

Stream  (0) 2015.01.26
FileWriter : FIndAll  (0) 2015.01.22
Thread 2  (0) 2015.01.14
Thread  (0) 2015.01.06
System  (0) 2015.01.06
Posted by af334
2015. 1. 14. 02:43
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

일반적으로 운영체제에서 스레드들에 대해 각각의 프로세서 또는 코어를 할당하여 스레드를 동시에 실행시킨다. 만일 컴퓨터에 스레드를 실행하기 위한 프로세서 또는 코어에 대한 여유가 없으면 스레드는 공유 프로세서 또는 코어를 사용하기 위해 대기를 한다.


운영체제는 이렇게 대기하고 있는 스레드를 어느 시점에 실행 시킬지를 결정하기 위해 스케쥴러를 사용한다. 스케쥴러는 운영체제에 따라 다른데 다음 리스트는 리눅스와 윈도우에서 사용되는 스케쥴러의 예이다.


***

출력결과가 첫 번째 스레드가 실행되는 것이 먼저 출력이 되었지만 스케쥴러에 따라 출력 순서가 달라 질 수 있다 



다단계 피드백 큐 스케쥴러를 포함한 다른 많은 스레드 스케쥴러에서 스레드 우선 순위 개념을 사용한다. 흔히 스케쥴러들은 선점형 스케쥴링(preemptive scheduling; 높은 우선 순위의 스레드를 먼저 실행)과 라운드 로빈 스케쥴링(round robin scheduling; 우선 순위가 같은 스레드는 시간을 분배하여 분배된 시간동안 번갈아 가면서 스레드를 실행) 이 결합된 형태로 구현되어 있다.


Thread 클래스는 void setPriority(int priority) 메소드와 int getPriority() 메소드를 통해 우선 순위를 지정하거나 우선 순위를 알아낼 수 있다. setPriority(int priority) 메소드는 Thread.MIN_PRIORITY에서 Thread.MAX_PRIORITY 범위에 있는 우선 순위 값을 스레드에 지정할 때 사용되는데, 기본 우선 순위값은 Thread.NORMAL_PRIORITY이다. int getPriority() 메소드는 스레드의 현재 우선 순위값을 반환한다.



***

스케쥴러마다 우선 순위를 조작하는 방법이 다를 수 있기 때문에 setPriority() 메소드를 사용할 경우 자바의 장점 중 하나인 플랫폼 이동성에 영향을 줄 수 있다. 예를 들어 몇몇 플랫폼 스케쥴러의 경우 우선 순위가 높은 스레드가 종료할 때까지 우선 순위가 낮은 스레드는 대기한다. 이런 스케쥴러의 경우 우선 순위가 낮은 스레드가 실행되기 위해 우선 순위가 높은 스레드가 종료할 때까지 많은 시간을 기다려야 하는 경우가 발생하기 때문에 무한 연기(indefinite postponement)또는 스터베이션(starvation)을 일으킬 수 있으며 또한 애플리케이션의 실행 속도를 심각하게 저하시킬 수 있다.




다음 코드는 main()메소드에서 각 스레드의 이름을 지정하고 name과 count를 출력 한 후 스레드를 대기(sleep)한다.



-----------------------------

package Thread;

public class CountingThreads02 {
    public static void main(String[] args){
        Runnable r=new Runnable() {
           
            @Override
            public void run() {
                String name=Thread.currentThread().getName();
                int count=0;
                while(true){
                    System.out.println(name+": "+count++);
                     try {
                        Thread.sleep(100);
                    } catch (InterruptedException ie) {
                    }
                }
            }
        };
       
        Thread thdA=new Thread(r);
        thdA.setName("A");
        Thread thdB=new Thread(r);
        thdB.setName("B");
        thdA.start();
        thdB.start();
    }
}



Threads A와 B를 100밀리 초동안 대기시키기 위해 Thread.sleep(100); 를 지정하였다. 이렇게 대기하여 각 스레드 실행을 좀 더 주기적으로 할 수 있다.


스레드는 계산이 많은 작업이나 파일 다운로드와 같이 시간이 많이 걸리는 작업을 수행하기 위해 메인 스레드에서 작업을 분리하여 다른 스레드에서 작업을 처리한다. 분리된 작업이 종료된 후 호출한 스레드는 분리된 스레드의 결과 처리를 할 준비를 하며 분리된 스레드가 종료될 때까지 대기한다.










'Java > Working-level Java' 카테고리의 다른 글

FileWriter : FIndAll  (0) 2015.01.22
Thread 3  (0) 2015.01.14
Thread  (0) 2015.01.06
System  (0) 2015.01.06
StringBuffer / StringBuilder  (0) 2015.01.03
Posted by af334
2015. 1. 14. 02:12
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package dataStructure;

import java.util.Vector;

public class Vector01 {
    public static void main(String[] args){
        Vector<String> vec=new Vector<String>();
        vec.add("도");
        vec.add("희");
        vec.add("귀");
        vec.add("여");
        vec.add("워");
        vec.add("아");
       
        System.out.println(vec.size());
        for(int i=0;i<vec.size();i++){
            System.out.println(vec.get(i));
        }
       
        if(vec.contains("도")){
            int idx=vec.indexOf("도");
            System.out.println(idx);
        }else{
            System.out.println("해당 요소 없음");
        }
        vec.removeAllElements();
        if(vec.isEmpty()){
            System.out.println("요소가 없당께로 씨방");
        }
    }
}

'Java' 카테고리의 다른 글

Java Streams - Java Stream Introduction  (0) 2015.01.14
ShowThread  (0) 2015.01.14
basic Vector  (0) 2015.01.14
encapsulating  (0) 2015.01.13
building a Stack structure  (0) 2015.01.13
Posted by af334
2015. 1. 14. 02:01
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package dataStructure;

import java.util.Vector;

public class exVector {
    public static void main(String[] args){
        Vector vlist=new Vector<>();
        System.out.println(vlist.capacity()); //용량
        System.out.println(vlist.size()); //요소의 갯수
        vlist.add("하하");
        vlist.add(1);
        vlist.add(true);
        vlist.add(new StringBuffer("히히"));
        System.out.println(vlist.capacity());
        System.out.println(vlist.size());
       
        for(int i=0;i<vlist.size();i++){
            Object obj=vlist.get(i);  //elementAt와 유사
            System.out.println(obj);
        }
       
        Vector<String> vlist2=new Vector<String>();
        vlist2.add("자바");
        vlist2.add("JSP");
        vlist2.add("Android");
        vlist2.add("Spring");
        vlist2.add("structs");

        for(int i=0;i<vlist2.size();i++){
            String str=vlist2.get(i);
            System.out.println(str);
        }
        ////////////////////////////////
        int arr[]={1,2,3,4,5,6,7,8,9,0};
        Vector<Integer> vlist3=new Vector<Integer>();
        for(int i=0;i<arr.length;i++){
            vlist3.add(arr[i]);
        }

        System.out.println(arr.length);
        vlist3.add(11);
        System.out.println(vlist3.capacity());
        System.out.println(vlist3.size());
    }
}

'Java' 카테고리의 다른 글

ShowThread  (0) 2015.01.14
an usage of Vector  (0) 2015.01.14
encapsulating  (0) 2015.01.13
building a Stack structure  (0) 2015.01.13
ProcessBuilder  (0) 2015.01.12
Posted by af334
2015. 1. 13. 22:31
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

캡슐화란 : 어떠한 정보를 특정 클래스 private 멤버변수에 메소드를 사용하여 담아두고 저장하는 것

  -> 사용할 때는 public 메소드로 접근하여 정보를 수정하거나 불러내서 사용한다



-------------------------


package dataStructure;

public class encapsulating {
   
        private int x;
        private int y;
 
        // 객체 생성시 x,y를 입력받는 형태의 생성자 정의
        public encapsulating(int x, int y) {
            this.x = x;
            this.y = y;
        }

        // x값을 입력받아 멤버변수 x에 담아 두기
        public void setX(int x) {
            this.x = x;
        }

        // y의 값을 입력받아 멤버변수y에 담아 두기
        public void setY(int y) {
            this.y = y;
        }

        // 증가시킬 x,y값을 입력받아 멤버변수에 x,y값을 증가시켜 담아두기
        public void moveXY(int x, int y) {
            this.x += x;
            this.y += y;
        }

        public int getX() {
            return this.x;
        }

        public int getY() {
            return this.y;
        }
    }

-===============



package dataStructure;


public class enMain {

    public static void main(String[] args) {
        encapsulating point = new encapsulating(100, 100);
        point.setX(200);
        point.setY(300);
        point.moveXY(50, 50);
       
        System.out.println(point.getX()+" "+point.getY());
    }

}




'Java' 카테고리의 다른 글

an usage of Vector  (0) 2015.01.14
basic Vector  (0) 2015.01.14
building a Stack structure  (0) 2015.01.13
ProcessBuilder  (0) 2015.01.12
UrlFrame, getting the page source and save as a txt file  (0) 2015.01.06
Posted by af334
2015. 1. 13. 00:23
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package dataStructure;

public class MyStack {
    private int top;
    private Object[] stack;
   
    public MyStack(int _size){
        top=0;
        stack=new Object[_size];
    }
   
    public void push(Object obj){
        if(top>=space()){
            System.out.println("Stack Push"+obj+" >> ERROR: Stack is fulled");
            return;
        }else{
            stack[top]=obj;
            top=top+1;
           
            System.out.println("Stack pushed");
            System.out.println(this.toString());
        }
    }
   
    public Object pop(){
        if(top==0){
            System.out.println("Stack pop >> ERROR: Stack is empty");
            return null;
        }else{
            top=top-1;
            Object obj=new Object();
            obj=stack[top];
            stack[top]=null;
           
            System.out.println("Stack Poped: "+obj);
            System.out.println(this.toString());
            return obj;
        }
    }
    public int size(){
        return top;
    }

    public int space(){
        return stack.length;
    }
   
    public boolean isEmpty(){
        return (top==0)?true:false;
    }
   
    public String toString(){
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<stack.length;i++){
            sb.append("["+stack[i]+"]");
        }
        return sb.toString();
    }
   
    public static void main(String[] args){
        MyStack myStack=new MyStack(2);
        myStack.push(10);
        myStack.push(50);
        myStack.pop();
        myStack.push(7);
        myStack.push(15);
        myStack.push(20);
        myStack.pop();
        myStack.pop();
        myStack.pop();
        myStack.push(12);
    }
}

'Java' 카테고리의 다른 글

basic Vector  (0) 2015.01.14
encapsulating  (0) 2015.01.13
ProcessBuilder  (0) 2015.01.12
UrlFrame, getting the page source and save as a txt file  (0) 2015.01.06
URL class, figuring the page source  (0) 2015.01.06
Posted by af334
2015. 1. 12. 19:45
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

자바는 외부 프로그램을 실행 시 출력 내용을 바로 확인 할 수 없고 버퍼에 저장 후 출력하는 방식으로 확인 해야 한다



JDK 1.4이하에는 exec()메소드를 이용해 외부 프로그램을 실행 할 수 있고

JDK1.5 이상에서는 ProcessBuilder 객체를 이용하여 외부 프로그램을 실행 시킬 수 있다.


Process 객체 생성 후 실행 커맨드를 다음과 같이 인자값으로 넣어 주어야 한다.


Process process=nw ProcessBuilder("cmd","dir","/w").start();


위와 같이 표현 한다면 cmd커맨드 창을 실행 후 dir /w 명령어를 실행 한다는 의미이다.




혹은 다음과 같이 배열을 이용해 표현할 수도 있다.


String[] cmd=new String[]{"cmd","dir","/w"};


Process process=new ProcessBuilder(cmd).start;


이렇게 실행한 결과를 버퍼에 저장한 후 표준 출력을 화면에 표시하여야 하는데 다음과 같이 표현할 수 있다.




BufferedReader stdOut=new BufferedReader( new InputStreamReader(process.getInputStream()));


//표준 출력 상태를 출력 

whle(str=stdOut.readLine())!=null){

System.out.println(str);

}



InputStreamReader 객체를 통하여 위 process 객체에 출력된 스트림을 입력 받아 버퍼에 저장 후

while 문을 통하여 버퍼에 저장된 내용을 펴시하여 준다.



package ProcessBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class opening {
    public static void main(String[] args){
   
        String addr="http://www.daum.net";
        Process process =null;
        String[] cmd=new String[]{"rundll32","url.dll","FileProtocolHandler",addr};
        String str=null;
       
        try {
            //프로세스 빌더를 통하여 외부 프로그램을 실행
            process=new ProcessBuilder(cmd).start();
           
            //외부 프로그램의 표준 출력 상태를 버퍼에 저장
            BufferedReader stdOut=new BufferedReader(new InputStreamReader(process.getInputStream()));
           
            //표준 출력 상태를 출력afd
            while((str=stdOut.readLine())!=null){
                System.out.println(str);
            }
        } catch (Exception e) {
                e.printStackTrace();
        }
    }
}


이렇게 하면 rundll32를 통하여 웹 브라우저 실행 후 네이버로 이동된다.





'Java' 카테고리의 다른 글

encapsulating  (0) 2015.01.13
building a Stack structure  (0) 2015.01.13
UrlFrame, getting the page source and save as a txt file  (0) 2015.01.06
URL class, figuring the page source  (0) 2015.01.06
CopyFile getting a new name from the console  (0) 2015.01.03
Posted by af334
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package IO;

import java.awt.Button;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;

import javax.swing.JFrame;

public class UrlFrame extends JFrame implements ActionListener{
    TextArea ta;
    TextField tf;
    Button btn;
    Button save;
    URL home;
    BufferedReader br;
   
    public UrlFrame(){
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("ViewHost");
        Panel p=new Panel();
        p.add(tf=new TextField("http://naver.com",40));
        p.add(btn=new Button("connect"));
        p.add(save=new Button("save"));
        ta=new TextArea();
        add("North",p);
        add("Center",ta);
        btn.addActionListener(this);
        save.addActionListener(this);
        tf.addActionListener(this);
        setVisible(true);
    }
   
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            if(e.getSource()==btn){
                home=new URL(tf.getText());
                br=new BufferedReader(new InputStreamReader(home.openStream(),"utf-8"));
               
                String line;
               
                while ((line=br.readLine())!=null) {
                    ta.append(line+"\n");
                }
                br.close();
            }else if(e.getSource()==save){
                createFile();
                save.setEnabled(false);
            }
        } catch (Exception e2) {       
        }
    }
    public void createFile(){
        try {
            PrintWriter pw=new PrintWriter(new BufferedWriter(new BufferedWriter(new FileWriter("/"+home.getHost()+ ".txt"))));
           
            pw.println(ta.getText());
            pw.flush();
            pw.close();
            ta.setText("");
        } catch (Exception e) {
        }
    }
   
    public static void main(String[] args){
        new UrlFrame();
    }
}

'Java' 카테고리의 다른 글

building a Stack structure  (0) 2015.01.13
ProcessBuilder  (0) 2015.01.12
URL class, figuring the page source  (0) 2015.01.06
CopyFile getting a new name from the console  (0) 2015.01.03
Fileclass methods  (0) 2015.01.03
Posted by af334
이전버튼 1 ··· 3 4 5 6 7 8 9 이전버튼