Java--线程
2015-08-22 19:49
609 查看
线程
继承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()让线程继续运行
但是多线程可能造成线程的死锁。即线程一直处于等待状态。
相关文章推荐
- struts/Servlet,action转到jsp后,路径问题(struts2,jsp路径,action路径,action跳转,相对路径,绝对路径)
- Spring jar下载地址:
- java并发编程---volatile
- Spring揭秘 读书笔记 四----方法注入
- Spring揭秘 读书笔记 四----方法注入
- java.exe 和 javac.exe ,jvm都是什么关系 什么是环境变量 环境变量的作用
- Struts(22)标签库详解
- 字符串转整数的java实现
- 每日5题(spring)
- Java- 对象构造与初始化
- java中接口和抽象类的区别
- java.net.UnknownHostException: Unable to resolve host "images.liqucn.com": No address associated wit
- Java 1.8 HashMap实现(译注)
- Struts(21)OGNL详解
- 使用Java 多线程编程 让三个线程轮流输出ABC,循环10次后结束
- spring3表达式语言(SpEL)
- 深入 Java Web 开发中的乱码问题
- Java- 多态和虚方法调用
- JAVA的反射机制与RTTI
- java中sublist的使用陷阱