Java--线程



线程



继承Thread类

public class TestThread1 {	
	public static void main(String args[]){
		Thread t = new MyThread(100);
		t.start();
	}
}

class MyThread extends Thread {
	private int n;;
	public MyThread( int n ){
		super();
		this.n=n;
	}
	public void run() {
		for(int i=0;i<n;i++) {
			System.out.print (" " + i);
		}
	}
}

向Thread构造方法传递Runnable对象

public class TestThread2 {
	public static void main(String args[]) {
		MyTask mytask = new MyTask(10);
		Thread thread = new Thread(mytask);
		thread.start();
		//thread.setDaemon(true);

		for(int i=0; i<6; i++) {	
			System.out.println("Main--" + i);
			try{
				Thread.sleep(500);
			}catch( InterruptedException e ){}
		}

	}
}

class MyTask implements Runnable {
	private int n;
	public MyTask(int n){
		this.n = n;
	}
	public void run() {
		for(int i=0; i<n; i++) {	
			System.out.println(" " + i);
			try{
				Thread.sleep(500);
			}catch( InterruptedException e ){}
		}
	}
}

public class TestThread4Anonymous {
	public static void main(String args[]) {

		new Thread(){
			public void run() {
				for(int i=0; i<10; i++)	
					System.out.println(i);
			}
		}.start();

		new Thread( ( ) -> { 
			for(int i=0; i<10; i++) 
				System.out.println(" "+ i); 
		} ).start();
	}
}



多线程程序示例

import java.util.*;
import java.text.*;
public class TestThread3 {
	public static void main(String args[]) {
		Counter c1 = new Counter(1);
		Thread t1 = new Thread(c1);
		Thread t2 = new Thread(c1);
		Thread t3 = new Thread(c1);
		Counter c2 = new Counter(2);
		Thread t4 = new Thread(c2);
		Thread t5 = new Thread(c2);
		Thread t6 = new Thread(c2);
		TimeDisplay timer = new TimeDisplay();
		Thread t7 = new Thread(timer);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		t7.start();
	}
}

class Counter implements Runnable {
	int id;
	Counter(int id){
		this.id = id;
	}
	public void run() {
		int i=0;
		while( i++<=10 ){
			System.out.println("ID: " + id + "  No. " + i);
			try{ Thread.sleep(10); } catch( InterruptedException e ){}
		}
	}
}

class TimeDisplay implements Runnable {
	public void run(){
		int i=0;
		while( i++<=3 ){
			System.out.println( 
				new SimpleDateFormat().format( new Date()));
			try{ Thread.sleep(40); } catch( InterruptedException e ){}
		}
	}
}







同时运行的线程需要共享数据,有时会造成混乱。所以必须考虑线程的同步问题。
synchronized用来表示不允许其它线程中途插入。

wait()是让线程暂停运行,进入等待;notify()让线程继续运行



但是多线程可能造成线程的死锁。即线程一直处于等待状态。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值