天天看點

Java多線程

Java多線程

class FirstThread extends Thread{

public void run(){

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

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

}

class Test{

public static void main(String args[]){

//生成線程類的對象

FirstThread ft=new FirstThread();

//啟動線程

ft.start();

//ft.run();不能這樣寫,否則變成單線程了

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

這裡有三個線程:1Main線程

2 ft對象建立線程3垃圾回收線程

class RunnableIm implements Runnable{

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

if(i==50){

try{

Thread.sleep(5000);

catch(Exception e){

System.out.println(e);

//生成一個Runnable接口實作類的對象

RunnableIm ri=new RunnableIm();

//将ri作為構造函數的參數傳入到Thread對象中,生成對象

Thread t=new Thread(ri);

//通知Thread對象,執行start()方法

//線程的優先級最大是10,最小是1,可以使用靜态常量來設定優先級

t.setPriority(Thread.MAX_PRIORITY);

t.start();

System.out.println(t.getPriority());

線程同步機制:

int i=100;

while(true){

//同步代碼塊,this是一個同步鎖

synchronized(this){

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

i--;

Thread.yield();

if(i<0){

break;

//生成兩個Thread對象,産生兩個線程體

Thread t1=new Thread(ri);

Thread t2=new Thread(ri);

//使用Thread的setName方法,設定線程名字

t1.setName("xianchenga");

t2.setName("xianchengb");

t1.start();

t2.start();

下一篇: java多線程

繼續閱讀