java多线程(四种创建方式,三种线程同步)
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
//继承Thread
class myThread1 extends Thread{
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
//线程同步方式一: synchronized静态代码块
synchronized (this){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
show();
m();
}
//线程同步方式二: synchronized方法
public synchronized void show(){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
//线程同步方式三:lock
public void m(){
try {
lock.lock();
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}finally {
lock.unlock();
}
}
}
//实现Runnable
class myThread2 implements Runnable{
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
//线程同步方式一: synchronized静态代码块
synchronized (myThread2.class){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
show();
m();
}
//线程同步方式二: synchronized方法
public synchronized void show(){
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
//线程同步方式三:lock
public void m(){
try {
lock.lock();
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}finally {
lock.unlock();
}
}
}
//实现Callable
class myThread3 implements Callable{
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
System.out.println(i);
}
return sum;
}
}
public class test {
public static void main(String[] args) {
//继承Thread
myThread1 myThread1 = new myThread1();
myThread1.start();
//实现Runnable
myThread2 myThread2 = new myThread2();
Thread thread1 = new Thread(myThread2);
thread1.start();
//实现Callable(一)
myThread3 myThread31 = new myThread3();
FutureTask futureTask1 = new FutureTask(myThread31);
try {
Object sum = futureTask1.get();
System.out.println(sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//实现Callable(二)
myThread3 myThread32 = new myThread3();
FutureTask futureTask2= new FutureTask(myThread32);
new Thread(futureTask2).start();
//线程池
ExecutorService service = Executors.newFixedThreadPool(2);
//执行Callable
service.submit(new myThread3());
//执行Runnable
service.execute(new myThread2());
//关闭线程
service.shutdown();
}
}