Java多线程
Thread类中的主要方法
- start():开启线程
- run():继承重写run()
- currentThread():返回当前线程
- getName():返回线程名
- setName():设置线程名
- yield():释放cpu执行权
- b.join():a线程阻塞并等待b线程执行完成
- stop():已过时,强制结束线程
- sleep():睡眠ms
- isAlive():是否存活
创建方式,jdk5.0前两种,jdk5.0后两种
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 线程池
1.继承Thread的方法
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
public class MyThreadTest1 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("thread1");
t1.start();
}
}
2.实现Runnable接口的方法
class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
public class MyThreadTest2 {
public static void main(String[] args) {
MyThread2 m1 = new MyThread2();
Thread t1 = new Thread(m1);
t1.setName("thread1");
t1.start();
}
}
3.实现Callable接口的方法
class MyThread3 implements Callable {
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
return sum;
}
}
public class MyThreadTest3 {
public static void main(String[] args) {
FutureTask futureTask = new FutureTask(new MyThread3());
Thread t1 = new Thread(futureTask);
t1.setName("thread1");
t1.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
4.使用线程池创建线程
class MyThread4 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
}
}
class MyThread5 implements Callable{
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
System.out.println(Thread.currentThread().getName() +
":" + i);
}
}
return sum;
}
}
public class MyThreadTest4 {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread4());
Future future = service.submit(new MyThread5());
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
service.shutdown();
}
}
线程同步方法:
- Synchronized (同步代码块,同步方法)同步监视器多个线程共用一个(共享数据时)
- Lock接口的实现类ReentrantLock对象的方法,lock.lock()、lock.unlock()
线程通信方法:
- wait() 阻塞
- notify()/notifyAll() 唤醒