如何实现线程:Java
实现方式1:继承Thread类,重写run函数
package y20220414 ;
public class BallThread extends Thread {
int x;
int y;
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
x += y;
}
}
}
package y20220414 ;
public class Thread01 {
public static void main ( String [ ] args) throws InterruptedException {
BallThread bt = new BallThread ( ) ;
bt. x = 100 ;
bt. y = 2 ;
bt. start ( ) ;
Thread . sleep ( 1000 ) ;
System . out. println ( bt. x) ;
}
}
实现方式2:Runnable接口,重写run函数
package y20220414 ;
public class BallRunnable implements Runnable {
int x;
int y;
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
x += y;
}
}
}
package y20220414 ;
public class Thread02 {
public static void main ( String [ ] args) throws InterruptedException {
BallRunnable br = new BallRunnable ( ) ;
br. x = 100 ;
br. y = 2 ;
new Thread ( br) . start ( ) ;
Thread . sleep ( 1000 ) ;
System . out. println ( br. x) ;
}
}
实现Tread类与Runnable接口之间的区别
实现Tread类创建线程 不能使用多个线程来共享一个对象的资源 实现Runnable接口创建线程 可以使用多个线程来共享同一个对象的资源
package y20220414 ;
public class YManage {
public static void main ( String [ ] args) {
YRunnable runnable = new YRunnable ( ) ;
runnable. x = 100 ;
Thread t1 = new Thread ( runnable) ;
t1. start ( ) ;
Thread t2 = new Thread ( runnable) ;
t2. start ( ) ;
YThread thread1 = new YThread ( ) ;
thread1. x = 100 ;
thread1. start ( ) ;
YThread thread2 = new YThread ( ) ;
thread2. x = 100 ;
thread2. start ( ) ;
System . out. println ( "使用Runnable: " + runnable. x) ;
System . out. println ( "使用Thread,Thread1: " + thread1. x) ;
System . out. println ( "使用Thread,Thread2: " + thread2. x) ;
}
}
package y20220414 ;
public class YThread extends Thread {
int x;
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
x += 2 ;
}
}
}
public class YRunnable implements Runnable {
int x;
@Override
public void run ( ) {
for ( int i = 0 ; i < 100 ; i++ ) {
x += 2 ;
}
}
}