Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Java中线程的使用

简单的使用线程

1 . 扩展java.lang.Thread类/***定义线程类*/public class MyThread extends Thread { public void run() { System.out.println("MyThread.run()"); }}
//使用线程MyThread myThread1 = new MyThread();MyThread myThread2 = new MyThread();myThread1.start();myThread2.start();
2 . 实现java.lang.Runnable接口/** * 实现Runnable接口的类*/ publicclass DoSomethingimplements Runnable {private String name;public DoSomething(String name) {this.name = name;} publicvoid run() {for (int i = 0; i < 5; i++) {for (long k = 0; k < 100000000; k++) ;System.out.println(name + ": " + i);} } }
/** * 测试Runnable类实现的多线程程序*/ publicclass TestRunnable {publicstaticvoid main(String[] args) {DoSomething ds1 = new DoSomething("阿三");DoSomething ds2 = new DoSomething("李四");Thread t1 = new Thread(ds1);Thread t2 = new Thread(ds2);t1.start(); t2.start(); } }

线程的同步与锁

线程的同步是为了防止多个线程访问一个数据对象时,对数据造成的破坏。
例如:两个线程ThreadA、ThreadB都操作同一个对象Foo对象,并修改Foo对象上的数据。public class Foo {privateint x = 100;publicint getX() {return x;} publicint fix(int y) {x = x - y; return x;} }public class MyRunnable implements Runnable {private Foo foo =new Foo(); public staticvoid main(String[] args) {MyRunnable r = new MyRunnable();Thread ta = new Thread(r,"Thread-A"); Thread tb = new Thread(r,"Thread-B"); ta.start(); tb.start(); } public void run() {for (int i = 0; i < 3; i++) {this.fix(30);try {Thread.sleep(1); } catch (InterruptedException e) {e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " :当前foo对象的x值= " + foo.getX());} } publicint fix(int y) {return foo.fix(y);} }运行结果:Thread-B :当前foo对象的x值= 40Thread-A :当前foo对象的x值= 40Thread-B :当前foo对象的x值= -20Thread-A :当前foo对象的x值= -20Thread-B :当前foo对象的x值= -80Thread-A :当前foo对象的x值= -80本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-03/129526.htm