スレッドの2の基本的な使い方

2155 ワード

Javaスレッドの2つの基本的な使用方法を示します.
Runnerコネクタ
 
public class TestThread1 {

	public static void main(String args[]) {

		Runner1 r = new Runner1();

		Thread t = new Thread(r);

		t.start();

		

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

			System.out.println("Main Thread:------" + i);

		}

	}

}



class Runner1 implements Runnable {



	public void run() {

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

			System.out.println("Runner1 :" + i);

		}

	}

}

/**

 :

Main Thread:------0

Runner1 :0

Main Thread:------1

Runner1 :1

Main Thread:------2

Runner1 :2

Main Thread:------3

Runner1 :3

Main Thread:------4

Runner1 :4

Main Thread:------5

Runner1 :5

Main Thread:------6

Runner1 :6

Main Thread:------7

Runner1 :7

Main Thread:------8

Runner1 :8

Main Thread:------9

Runner1 :9

Main Thread:------10

Main Thread:------11

Runner1 :10

Main Thread:------12

Runner1 :11

Main Thread:------13

Runner1 :12

Main Thread:------14

Runner1 :13

Runner1 :14

**/

Thread
 
 
public class TestThread1 {

	public static void main(String args[]) {

		Runner1 r = new Runner1();

		r.start();



		

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

			System.out.println("Main Thread:------" + i);

		}

	}

}





class Runner1 extends Thread {

	public void run() {

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

			System.out.println("Runner1 :" + i);

		}

	}

}

/**

 :

Main Thread:------0

Main Thread:------1

Runner1 :0

Main Thread:------2

Runner1 :1

Main Thread:------3

Runner1 :2

Main Thread:------4

Runner1 :3

Main Thread:------5

Runner1 :4

Main Thread:------6

Runner1 :5

Main Thread:------7

Runner1 :6

Main Thread:------8

Runner1 :7

Main Thread:------9

Runner1 :8

Main Thread:------10

Runner1 :9

Runner1 :10

Runner1 :11

Runner1 :12

Runner1 :13

Runner1 :14

Main Thread:------11

Main Thread:------12

Main Thread:------13

Main Thread:------14

**/

 
実は1つのcupは同じ時間に1つのスレッドしか実行されませんが、実行速度が速く、同時に実行しているような感じがします.
スレッドにはいくつかの方法と知識点があります.
sleep()
interrupt()
stop()
join()
yield()
優先度の設定