线程的创建
方式一:Thread
public class dome {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
for(int i=1;i<=5;i++){
System.out.println("主线程"+i);
}
}
}
public class MyThread extends Thread{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("MyThread线程"+i);
}
}
}
方式二:Runnable
public class dome {
public static void main(String[] args) {
Runnable r = new MyRunnable();
new Thread(r).start();
for(int i=1;i<=5;i++){
System.out.println("主线程"+i);
}
}
}
public class MyRunnable implements Runnable{
@Override
public void run() {
for(int i=1;i<=5;i++){
System.out.println("MyRunnable"+i);
}
}
}
方式三:Callable
public class dome {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//3.创建一个Callable对象
Callable c = new MaCallable(100);
//4.把Callable对象封装成一个FutureTask对象(任务对象)
FutureTask<String> f = new FutureTask<>(c);
//作用
//1.是一个任务对象,实现了Ruuable类
//2.可以用get()方法获取任务执行完后的结果
new Thread(f).start();
//获取执行完之后的结果
//如果此时还未执行完,则在此等待
String s = f.get();
System.out.println(s);
}
}
//1.实现Callable接口
public class MaCallable implements Callable<String> {
private int n;
public MaCallable(int n){
this.n=n;
}
//2.重写call方法
@Override
public String call() throws Exception {
int sum=0;
for(int i=1;i<=n;i++){
sum+=i;
}
return "1-"+n+"的和为:"+sum;
}
}
Thread常用方法
public class dome {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread t1 = new MyThread("1号");
// t1.setName("1号");//设置线程名称
t1.start();
Thread t2 = new MyThread("2号");
// t1.setName("2号");
t2.start();
Thread t = Thread.currentThread();
for(int i=1;i<=5;i++){
System.out.println(t.getName()+"线程"+i);
}
}
}
public class MyThread extends Thread{
public MyThread(String name){
super(name);
}
@Override
public void run() {
Thread t = Thread.currentThread();//用来获取线程名称
for(int i=0;i<5;i++){
System.out.println(t.getName()+"线程"+i);
}
}
}
public class dome {
public static void main(String[] args) throws ExecutionException, InterruptedException {
for(int i=1;i<=5;i++){
if(i==3){
//休眠5秒
Thread.sleep(5000);
}
System.out.println(i);
}
//join:让当前线程先跑完
Thread t1 = new MyThread("1号");
t1.start();
t1.join();
Thread t2 = new MyThread("2号");
t2.start();
Thread t3 = new MyThread("3号");
t3.start();
t2.join();
}
}
线程同步
线程安全
线程同步的几种方式
1.同步代码块 (比2好)
public void dr(int n) {
String name = Thread.currentThread().getName();
synchronized (this) {
//实力方法建议用this,静态方法建议用。class
if(n<=num){
System.out.println(name+"取钱"+n);
num-=n;
System.out.println(name+"剩"+num);
}
else {
System.out.println(name+"不足");
}
}
}
2.同步方法(可读性好)
public synchronized void dr(int n) {
String name = Thread.currentThread().getName();
if(n<=num){
System.out.println(name+"取钱"+n);
num-=n;
System.out.println(name+"剩"+num);
}
else {
System.out.println(name+"不足");
}
}