IT 공부/Java
Thread 구현
toraa
2022. 7. 6. 16:12
스레드
. 멀티태스킹 - 하나의 응용프로그램을 여러개의 프로세스로 구성하여 각 프로세서가 하나의 작업을 처리하도록 하는 기법
- 고유한 메모리 영역을 보유하고 독립적으로 실행된다.
. 멀티스레딩 - 하나의 응용프로그램을 여러작업 코드로 분할해서 작업의 개수만큼 스레드를 생성하여 각 스레드별로 처리하는 기법
- 모든 스레드는 응용프로그램내의 자원과 메모리를 공유한다.
>> 자바는 멀티스레딩을 지원한다.
스레드의 생명주기
생성
|
start( ) - 실행대기상태
|
run( ) - cpu의 스케줄러에 의해 실행상태
|
wait( ) -- blocked(지연상태) --> notify( ) --> 다시 준비대기상태 --> 실행완료 후 종료
또는
sleep( ) -- blocked(지연상태) --> 시간경과하면 ---> 다시 준비대기상태 --> 실행완료 후 종료
스레드 구현
. Thread 클래스
. Runnable 인터페이스 --> Thread 객체 생성
. try~~ catch(InterruptException e)
. run( )메소드안에 스레드로 할 부분을 구현해 놓는다
class TimeTh extends Thread{
int n=0;
@Override
public void run() { //스레드로 처리할 코드를 정의해 놓는다.
while(true) {
System.out.println(n);
n++;
try {
sleep(1000); // 1000 = 1초
}catch (InterruptedException e) {
return;
}
}
}
}
public class Thread1 {
public static void main(String[] args) {
TimeTh th = new TimeTh();
th.start();
}
}
package 구현;
class TestTh extends Thread{
TestTh(String str){
super(str);
}
public void run() {
for(int i=1; i<=100; i++) {
System.out.println(getName()+i+"\t");
if(i%10==0) {
System.out.println();
}
}
}
}
public class Thread2 {
public static void main(String[] args) {
TestTh th1 = new TestTh("subA");
TestTh th2 = new TestTh("subB");
th1.run();
th2.run();
for(int i=1; i<=100; i++) {
System.out.println("main"+i+"\t");
if(i%10==0) {
System.out.println();
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
System.out.println("날 막을 순 없지..ㅇㅅㅇ");
}
}
}
}
}
package 구현;
import javax.swing.JOptionPane;
public class Thread3 {
public static void main(String[] args) throws InterruptedException {
for(int i=0; i<=100; i++) {
System.out.println(i+",");
if(i%10 ==0) {
System.out.println();
}
Thread.sleep(100);
}
String name = JOptionPane.showInputDialog("너의 이름은 ㅇㅅㅇ");
System.out.println(name);
Thread.interrupted();
}
}
package 구현;
import javax.swing.JOptionPane;
class TestTh2 extends Thread {
public void run() {
for(int i=0, j=0; i<20; i++, j++) {
System.out.println(i+j);
try {
sleep(1000);
}catch (Exception e) {
}
}
}
}
public class Thread4 {
public static void main(String[] args) {
TestTh2 th = new TestTh2();
th.start();
String name = JOptionPane.showInputDialog("이름을 말하랏");
System.out.println("이름은 "+name+"입니당");
}
}
package 구현;
class Test3 implements Runnable{
@Override
public void run() {
for(int i=0; i<=100; i++) {
System.out.println(Thread.currentThread().getName()+"뀨잉\t");
if(i%10==0) {
System.out.println();
}
}
}
}
public class Thread5 {
public static void main(String[] args) {
Test3 test1 = new Test3();
Test3 test2 = new Test3();
Thread th1 = new Thread(test1, "첫번째");
Thread th2 = new Thread(test2, "두번째");
th1.start();
th2.start();
}
}
package 구현;
//1~100까지 10개르 한줄로 0.5초마다 출력
class MyTh extends Thread{
public void run() {
for(int i=1; i<=100; i++) {
System.out.println(i);
if(i%10==0) {
System.out.println();
}
}
try {
sleep(500);
}catch (Exception e) {
}return;
}
}
public class Thread6 {
public static void main(String[] args) {
MyTh th = new MyTh();
th.start();
}
}
package 구현;
import java.awt.*;
import javax.swing.*;
class Flickering extends JLabel implements Runnable{
public Flickering(String text) {
super(text);
setOpaque(true);
Thread th = new Thread(this);
th.start();
}
@Override
public void run() {
int n=0;
while(true) {
if(n==0) {
setBackground(Color.yellow);
}else {
setBackground(Color.green);
}
if(n==0) n=1;
else n=0;
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
return;
}
}
}
}
public class Thread8 extends JFrame {
public Thread8() {
setTitle("깜빡이");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
Flickering f1 = new Flickering("깜빡");
JLabel label = new JLabel("안깜빡");
Flickering f2 = new Flickering("여기도 깜빡");
c.add(f1);
c.add(label);
c.add(f2);
setSize(350,350);
setVisible(true);
}
public static void main(String[] args) {
new Thread8();
}
}
package 구현;
import java.awt.*;
import javax.swing.*;
class Timer implements Runnable{
JLabel timerLabel;
Timer(JLabel timerLabel){
this.timerLabel = timerLabel;
}
@Override
public void run() {
String str = JOptionPane.showInputDialog("이제부터 카운트를 시작합니당. 몇부터 시작할까요?");
int t = Integer.parseInt(str);
for(int i=t; i>=0; i--) {
timerLabel.setText(Integer.toString(i));
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
return;
}
}
timerLabel.setFont(new Font("Gothic",Font.ITALIC,30));
timerLabel.setForeground(Color.WHITE);
timerLabel.setText("끄읏ㅇㅅㅇ!!");
Thread.interrupted();
}
}
public class Thread9 extends JFrame {
public Thread9() {
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.black);
JLabel timerLabel = new JLabel();
timerLabel.setForeground(Color.yellow);
timerLabel.setFont(new Font("Gothic",Font.BOLD,80));
Timer tr = new Timer(timerLabel);
Thread th = new Thread(tr);
c.add(timerLabel);
setSize(300,150);
setVisible(true);
th.start();
}
public static void main(String[] args) {
new Thread9();
}
}
package 구현;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Thread10 extends JFrame{
public Thread10() {
setContentPane(new MyPanel());
setSize(getMaximumSize());
setVisible(true);
}
class MyPanel extends JLabel implements Runnable{
int x=200, y=800;
public MyPanel() {
setBackground(Color.black);
setOpaque(true);
addMouseMotionListener(new MyListener());
Thread th = new Thread(this);
th.start();
}
@Override
public void run() {
while(true) {
x = x+2;
y = y-(3/2);
try {
Thread.sleep(50);
}catch (InterruptedException e) {
return;
}
repaint();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillArc(x-200, y-200, 400, 400, 0, 360);
}
class MyListener implements MouseMotionListener{
@Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}
}
}
public static void main(String[] args) {
new Thread10();
}
}
package 구현;
class SumTh extends Thread{
private long sum;
public long getSum() {
return sum;
}
public void setSum(long sum){
this.sum = sum;
}
public void run() {
for(int i=1; i<=100; i++) {
sum += i;
try {
sleep(50);
}catch(InterruptedException e) {}
System.out.println(sum);
}
}
}
public class Thread11 {
public static void main(String[] args) {
SumTh sumth = new SumTh();
sumth.start();
try {
sumth.join();
}catch(InterruptedException e){}
System.out.println("1~100까지 합은 "+sumth.getSum());
}
}
package 구현;
//yield():다른 스레드에게 양보
class ThA extends Thread{
public boolean stop = false;
public boolean work = true;
public void run() {
while(!stop) {
if(work) {
System.out.println("ThreadA 작업내용");
try {
Thread.sleep(500);
}catch(InterruptedException e) {}
}else {
Thread.yield();
}
}
System.out.println("ThreadA 종료");
}
}
class ThB extends Thread{
public boolean stop = false;
public boolean work = true;
public void run(){
while(!stop){
if(work){
System.out.println("ThreadB 작업내용");
try {
Thread.sleep(500);
}catch (InterruptedException e){}
}else {
Thread.yield();
}
}
System.out.println("ThreadB 종료");
}
}
public class Thread12 {
public static void main(String[] args) {
ThA th1 = new ThA();
ThB th2 = new ThB();
th1.start();
th2.start();
try {
Thread.sleep(3000);
}catch (InterruptedException e) {}
th1.work = false;
try {
Thread.sleep(3000);
}catch(InterruptedException e) {}
th1.work = true;
try {
Thread.sleep(3000);
}catch (InterruptedException e) {}
th1.stop=true;
th2.stop=true;
}
}
package 구현;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Thread13 extends JFrame {
Thread13(){
Container c = getContentPane();
c.setBackground(Color.blue);
c.add(new ClockLabel(), BorderLayout.CENTER);
setSize(500,200);
setVisible(true);
}
class ClockLabel extends JLabel implements Runnable{
ClockLabel(){
setText(makeTime());
setFont(new Font("이탤릭",Font.ITALIC,100));
setForeground(Color.WHITE);
setBackground(Color.BLUE);
setHorizontalAlignment(JLabel.CENTER);
Thread th = new Thread(this);
th.start();
}
@Override
public void run() {
while(true) {
setText(makeTime());
try{
Thread.sleep(1000);
}catch(InterruptedException e) {}
}
}
}
public String makeTime() {
String timeText = null;
Calendar now = Calendar.getInstance();
int time = now.get(Calendar.HOUR_OF_DAY);
int min = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
timeText = Integer.toString(time);
timeText = timeText.concat(":");
timeText = timeText.concat(Integer.toString(min));
timeText = timeText.concat(":");
timeText = timeText.concat(Integer.toString(second));
return timeText;
}
public static void main(String[] args) {
new Thread13();
}
}
package 구현;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Thread14 extends JFrame {
public Thread14() {
MyPanel mp = new MyPanel();
setContentPane(mp);
setSize(1800,500);
setVisible(true);
}
public static void main(String[] args) {
new Thread14();
}
}
@SuppressWarnings("serial")
class MyPanel extends JPanel{
MyPanel(){
setLayout(null);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
MyThread bubbleTh = new MyThread(e.getX(), e.getY());
bubbleTh.start();
}
});
}
class MyThread extends Thread{
JLabel bubble;
public MyThread(int bubbleX, int bubbleY) {
ImageIcon img = new ImageIcon("images/1.png");
bubble = new JLabel(img);
bubble.setSize(img.getIconWidth(), img.getIconHeight());
bubble.setLocation(bubbleX, bubbleY);
add(bubble);
repaint();
}
public void run() {
while(true) {
int x = bubble.getX();
int y = bubble.getY()-1;
if(y<0) {
remove(bubble);
repaint();
return;
}
bubble.setLocation(x,y);
repaint();
try {
sleep(20);
}catch(InterruptedException e) {}
}
}
}
}